Using-QtWebKit-and-QML-with-PySide: Difference between revisions

From Qt Wiki
Jump to navigation Jump to search
No edit summary
 
No edit summary
Line 1: Line 1:
'''English''' [http://qt-devnet.developpez.com/tutoriels/python/pyside/qml/qtwebkit/ French] ''[qt-devnet.developpez.com]''
[[Category:LanguageBindings::PySide]]<br />[[Category:Snippets]]<br />[[Category:Developing_with_Qt::Qt Quick]]<br />[[Category:Developing_with_Qt::Qt Quick::QML]]<br />[[Category:Developing_with_Qt::Qt Quick::Tutorial]]<br />[[Category:Developing_with_Qt::QtWebKit]]


=Using QtWebKit and <span class="caps">QML</span> with PySide=
[toc align_right=&quot;yes&amp;quot; depth=&quot;3&amp;quot;]


This [[PySide]] tutorial shows you how to integrate Python code and [[QtWebKit]] together with <span class="caps">QML</span>, so you can have <span class="caps">HTML</span> content and program logic inside a <span class="caps">QML</span> application while still being able to send messages back and forth between the JavaScript context inside the WebView and the Python world. It uses <span class="caps">JSON</span>, alert() and evaluateJavaScript() to exchange arbitrary data structures (values, lists, dictionaries) between Python and JavaScript in the WebView.
'''English''' &quot;French&amp;quot;:http://qt-devnet.developpez.com/tutoriels/python/pyside/qml/qtwebkit/


==WebKitView.py==
= Using QtWebKit and QML with PySide =


===Importing required modules===
This [[PySide]] tutorial shows you how to integrate Python code and [[QtWebKit]] together with QML, so you can have HTML content and program logic inside a QML application while still being able to send messages back and forth between the JavaScript context inside the WebView and the Python world. It uses JSON, alert&amp;amp;#40;&amp;#41; and evaluateJavaScript() to exchange arbitrary data structures (values, lists, dictionaries) between Python and JavaScript in the WebView.


The '''sys''' module is used to get command line arguments, '''time''' is used to get the current time and '''json''' is used to en- and decode data structures to/from <span class="caps">JSON</span>.
== WebKitView.py ==


===Send and receive helper functions===
=== Importing required modules ===


These two functions send data to the WebView and receive data from the WebView. '''sendData''' simply transforms the data into <span class="caps">JSON</span> and calls '''receiveJSON''' (as defined in the <span class="caps">HTML</span> file) via the '''evaluateJavaScript''' method to put the data there. '''receiveData''' is connected to the '''alert''' signal of the WebView object, and gets a string as parameter, which is decoded as <span class="caps">JSON</span> and processed. When we want to set the rotation, we simply set the <span class="caps">QML</span> property “rotation” on the WebView object, which will rotate it in our view.
The '''sys''' module is used to get command line arguments, '''time''' is used to get the current time and '''json''' is used to en- and decode data structures to/from JSON.


===Putting it all together===
<code><br />import sys<br />import time<br />import json


Instantiate a new QApplication, a new QDeclarativeView and load the <span class="caps">QML</span> file. We also set the render hints to SmoothPixmapTransform, which makes the rotated WebView content look nicer (if you want more performance, remove this line). We then set the '''url''' property of our WebView to our <span class="caps">HTML</span> file, and finally make sure that we connect to the '''alert''' signal of the WebView, which gets emitted when the JavaScript code inside the WebView executes '''alert()'''.
from PySide import QtGui, QtDeclarative<br /></code>


==WebKitView.qml==
=== Send and receive helper functions ===


This one is relatively unspectacular. Simply import QtWebKit (for this you have to install the '''libqtwebkit4-declarative''' package) and create a new WebView. The '''settings.javascriptEnabled''' part here is key – without it, JavaScript inside the WebView will not be executed.
These two functions send data to the WebView and receive data from the WebView. '''sendData''' simply transforms the data into JSON and calls '''receiveJSON''' (as defined in the HTML file) via the '''evaluateJavaScript''' method to put the data there. '''receiveData''' is connected to the '''alert''' signal of the WebView object, and gets a string as parameter, which is decoded as JSON and processed. When we want to set the rotation, we simply set the QML property &quot;rotation&amp;quot; on the WebView object, which will rotate it in our view.


==WebKitView.html==
<code><br />def sendData(data):<br /> global rootObject<br /> print 'Sending data:', data<br /> json_str = json.dumps(data).replace('&quot;', '&quot;')<br /> rootObject.evaluateJavaScript('receiveJSON(&quot;s&amp;quot;)' json_str)


===<span class="caps">HTML</span> header===
def receiveData(json_str):<br /> global rootObject


Here’s how we start out with the <span class="caps">HTML</span> file:
data = json.loads(json_str)<br /> print 'Received data:', data


===JavaScript send and receive functions===
if len(data)  2 and data[0]  'setRotation':<br /> rootObject.setProperty('rotation', data[1])<br /> else:<br /> sendData({'Hello': 'from PySide', 'itsNow': int(time.time())})<br /></code>


The '''sendJSON''' function will be called by our code (see below), the '''receiveJSON''' function will be called from Python by executing JavaScript code on the WebView.
=== Putting it all together ===
 
Instantiate a new QApplication, a new QDeclarativeView and load the QML file. We also set the render hints to SmoothPixmapTransform, which makes the rotated WebView content look nicer (if you want more performance, remove this line). We then set the '''url''' property of our WebView to our HTML file, and finally make sure that we connect to the '''alert''' signal of the WebView, which gets emitted when the JavaScript code inside the WebView executes '''alert&amp;amp;#40;&amp;#41;'''.
 
<code><br />app = QtGui.QApplication(sys.argv)
 
view = QtDeclarative.QDeclarativeView()<br />view.setRenderHints(QtGui.QPainter.SmoothPixmapTransform)<br />view.setSource(''file''.replace('.py', '.qml'))<br />rootObject = view.rootObject()<br />rootObject.setProperty('url', ''file''.replace('.py', '.html'))<br />rootObject.alert.connect(receiveData)<br />view.show()
 
app.exec_()<br /></code>
 
== WebKitView.qml ==
 
This one is relatively unspectacular. Simply import QtWebKit (for this you have to install the '''libqtwebkit4-declarative''' package) and create a new WebView. The '''settings.javascriptEnabled''' part here is key - without it, JavaScript inside the WebView will not be executed.
 
<code><br />import QtWebKit 1.0
 
WebView { settings.javascriptEnabled: true; width: 400; height: 280 }<br /></code>
 
== WebKitView.html ==
 
=== HTML header ===


===Callbacks for our buttons===
Here's how we start out with the HTML file:


We’ll be using the '''sendJSON''' method to send data when the buttons are clicked. Here are the functions that generate the messages and then send the data to Python:
<code><br />&amp;lt;html&amp;amp;gt;<br /> &amp;lt;head&amp;amp;gt;<br /> &amp;lt;script language=&quot;javascript&amp;quot; type=&quot;text/javascript&amp;quot;&amp;gt;<br /></code>


===The <span class="caps">HTML</span> body contents===
=== JavaScript send and receive functions ===


This is the rest of the <span class="caps">HTML</span> file, which simply gives some text, the input field, two buttons and a preformatted text element where we will insert received stuff from Python:
The '''sendJSON''' function will be called by our code (see below), the '''receiveJSON''' function will be called from Python by executing JavaScript code on the WebView.


==How the example app looks like==
<code><br /> function sendJSON(data) {<br /> alert&amp;amp;#40;JSON.stringify(data&amp;amp;#41;);<br /> }<br /> function receiveJSON(data) {<br /> element = document.getElementById('received');<br /> element. innerHTML ''= &quot;&quot;'' data;<br /> }<br /></code>


Once you have got all three files, start the example app like this: '''python WebKitView.py'''
=== Callbacks for our buttons ===
 
We'll be using the '''sendJSON''' method to send data when the buttons are clicked. Here are the functions that generate the messages and then send the data to Python:


[[Image:5226208800_5a1b8351f5_z.jpg|Screenshot of WebKitView inside QML with Python]]
<code><br /> function setRotation() {<br /> element = document.getElementById('rotate');<br /> angle = parseInt(element.value);<br /> message = ['setRotation', angle];<br /> sendJSON(message);<br /> }<br /> function sendStuff() {<br /> sendJSON([42, 'PySide', 1.23, true, {'a':1,'b':2}]);<br /> }<br /></code>


===Categories:===
=== The HTML body contents ===


* [[:Category:Developing with Qt|Developing_with_Qt]]
This is the rest of the HTML file, which simply gives some text, the input field, two buttons and a preformatted text element where we will insert received stuff from Python:
** [[:Category:Developing with Qt::Qt-Quick|Qt Quick]]
* [[:Category:Developing with Qt::Qt-Quick::QML|QML]]


* [[:Category:Developing with Qt::Qt-Quick::Tutorial|Tutorial]]
<code><br /> &amp;lt;/script&amp;amp;gt;<br /> &amp;lt;/head&amp;amp;gt;<br /> &amp;lt;body&amp;amp;gt;<br /> &lt;h2&amp;gt;PySide + QML + WebKit FTW&amp;lt;/h2&amp;gt;<br /> &lt;p&amp;gt;<br /> Set rotation:<br /> &amp;lt;input type=&quot;text&amp;quot; size=&quot;5&amp;quot; id=&quot;rotate&amp;quot; value=&quot;10&amp;quot;/&amp;amp;gt;<br /> &lt;button onclick=setRotation()&gt;Click me now!&lt;/button&amp;gt;<br /> &lt;/p&amp;gt;<br /> &lt;p&amp;gt;<br /> Send arbitrary data structures:<br /> &lt;button onclick=sendStuff()&gt;No, click me!&lt;/button&amp;gt;<br /> &lt;/p&amp;gt;<br /> &lt;p&amp;gt;Received stuff:&lt;/p&amp;gt;<br /> &lt;pre id=&quot;received&amp;quot;&gt;&lt;/pre&amp;gt;<br /> &amp;lt;/body&amp;amp;gt;<br />&amp;lt;/html&amp;amp;gt;<br /></code>


* [[:Category:Developing with Qt::QtWebKit|QtWebKit]]
== How the example app looks like ==


* [[:Category:LanguageBindings|LanguageBindings]]
Once you have got all three files, start the example app like this: '''python WebKitView.py'''
** [[:Category:LanguageBindings::PySide|PySide]]
* [[:Category:snippets|snippets]]

Revision as of 14:46, 23 February 2015






[toc align_right="yes&quot; depth="3&quot;]

English "French&quot;:http://qt-devnet.developpez.com/tutoriels/python/pyside/qml/qtwebkit/

Using QtWebKit and QML with PySide

This PySide tutorial shows you how to integrate Python code and QtWebKit together with QML, so you can have HTML content and program logic inside a QML application while still being able to send messages back and forth between the JavaScript context inside the WebView and the Python world. It uses JSON, alert&amp;#40;&#41; and evaluateJavaScript() to exchange arbitrary data structures (values, lists, dictionaries) between Python and JavaScript in the WebView.

WebKitView.py

Importing required modules

The sys module is used to get command line arguments, time is used to get the current time and json is used to en- and decode data structures to/from JSON.

<br />import sys<br />import time<br />import json

from PySide import QtGui, QtDeclarative<br />

Send and receive helper functions

These two functions send data to the WebView and receive data from the WebView. sendData simply transforms the data into JSON and calls receiveJSON (as defined in the HTML file) via the evaluateJavaScript method to put the data there. receiveData is connected to the alert signal of the WebView object, and gets a string as parameter, which is decoded as JSON and processed. When we want to set the rotation, we simply set the QML property "rotation&quot; on the WebView object, which will rotate it in our view.

<br />def sendData(data):<br /> global rootObject<br /> print 'Sending data:', data<br /> json_str = json.dumps(data).replace('&quot;', '&quot;')<br /> rootObject.evaluateJavaScript('receiveJSON(&quot;s&amp;quot;)' json_str)

def receiveData(json_str):<br /> global rootObject

data = json.loads(json_str)<br /> print 'Received data:', data

if len(data)  2 and data[0]  'setRotation':<br /> rootObject.setProperty('rotation', data[1])<br /> else:<br /> sendData({'Hello': 'from PySide', 'itsNow': int(time.time())})<br />

Putting it all together

Instantiate a new QApplication, a new QDeclarativeView and load the QML file. We also set the render hints to SmoothPixmapTransform, which makes the rotated WebView content look nicer (if you want more performance, remove this line). We then set the url property of our WebView to our HTML file, and finally make sure that we connect to the alert signal of the WebView, which gets emitted when the JavaScript code inside the WebView executes alert&amp;#40;&#41;.

<br />app = QtGui.QApplication(sys.argv)

view = QtDeclarative.QDeclarativeView()<br />view.setRenderHints(QtGui.QPainter.SmoothPixmapTransform)<br />view.setSource(''file''.replace('.py', '.qml'))<br />rootObject = view.rootObject()<br />rootObject.setProperty('url', ''file''.replace('.py', '.html'))<br />rootObject.alert.connect(receiveData)<br />view.show()

app.exec_()<br />

WebKitView.qml

This one is relatively unspectacular. Simply import QtWebKit (for this you have to install the libqtwebkit4-declarative package) and create a new WebView. The settings.javascriptEnabled part here is key - without it, JavaScript inside the WebView will not be executed.

<br />import QtWebKit 1.0

WebView { settings.javascriptEnabled: true; width: 400; height: 280 }<br />

WebKitView.html

HTML header

Here's how we start out with the HTML file:

<br />&amp;lt;html&amp;amp;gt;<br /> &amp;lt;head&amp;amp;gt;<br /> &amp;lt;script language=&quot;javascript&amp;quot; type=&quot;text/javascript&amp;quot;&amp;gt;<br />

JavaScript send and receive functions

The sendJSON function will be called by our code (see below), the receiveJSON function will be called from Python by executing JavaScript code on the WebView.

<br /> function sendJSON(data) {<br /> alert&amp;amp;#40;JSON.stringify(data&amp;amp;#41;);<br /> }<br /> function receiveJSON(data) {<br /> element = document.getElementById('received');<br /> element. innerHTML ''= &quot;&quot;'' data;<br /> }<br />

Callbacks for our buttons

We'll be using the sendJSON method to send data when the buttons are clicked. Here are the functions that generate the messages and then send the data to Python:

<br /> function setRotation() {<br /> element = document.getElementById('rotate');<br /> angle = parseInt(element.value);<br /> message = ['setRotation', angle];<br /> sendJSON(message);<br /> }<br /> function sendStuff() {<br /> sendJSON([42, 'PySide', 1.23, true, {'a':1,'b':2}]);<br /> }<br />

The HTML body contents

This is the rest of the HTML file, which simply gives some text, the input field, two buttons and a preformatted text element where we will insert received stuff from Python:

<br /> &amp;lt;/script&amp;amp;gt;<br /> &amp;lt;/head&amp;amp;gt;<br /> &amp;lt;body&amp;amp;gt;<br /> &lt;h2&amp;gt;PySide + QML + WebKit FTW&amp;lt;/h2&amp;gt;<br /> &lt;p&amp;gt;<br /> Set rotation:<br /> &amp;lt;input type=&quot;text&amp;quot; size=&quot;5&amp;quot; id=&quot;rotate&amp;quot; value=&quot;10&amp;quot;/&amp;amp;gt;<br /> &lt;button onclick=setRotation()&gt;Click me now!&lt;/button&amp;gt;<br /> &lt;/p&amp;gt;<br /> &lt;p&amp;gt;<br /> Send arbitrary data structures:<br /> &lt;button onclick=sendStuff()&gt;No, click me!&lt;/button&amp;gt;<br /> &lt;/p&amp;gt;<br /> &lt;p&amp;gt;Received stuff:&lt;/p&amp;gt;<br /> &lt;pre id=&quot;received&amp;quot;&gt;&lt;/pre&amp;gt;<br /> &amp;lt;/body&amp;amp;gt;<br />&amp;lt;/html&amp;amp;gt;<br />

How the example app looks like

Once you have got all three files, start the example app like this: python WebKitView.py