Qt wiki will be updated on October 12th 2023 starting at 11:30 AM (EEST) and the maintenance will last around 2-3 hours. During the maintenance the site will be unavailable.

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

From Qt Wiki
Jump to navigation Jump to search
No edit summary
 
No edit summary
 
(10 intermediate revisions by 5 users not shown)
Line 1: Line 1:
'''English''' [http://qt-devnet.developpez.com/tutoriels/python/pyside/qml/qtwebkit/ French] ''[qt-devnet.developpez.com]''


=Using QtWebKit and <span class="caps">QML</span> with PySide=


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.
[[Category:PySide]]
[[Category:Snippets]]
[[Category:Developing_with_Qt::Qt Quick]]
[[Category:Developing_with_Qt::Qt Quick::QML]]
[[Category:Developing_with_Qt::Qt Quick::Tutorial]]
[[Category:Developing_with_Qt::QtWebKit]]


==WebKitView.py==
{| class="wikitable"
|-
| style="background: #ff6961;text-align: center;"| Attention
|-
| This is a page dedicated to PySide (Qt4). For recent development on PySide2 (Qt5) and PySide6 (Qt6) refer to [[Qt for Python]]
|}


===Importing required modules===
'''English''' [http://qt-devnet.developpez.com/tutoriels/python/pyside/qml/qtwebkit/ French]


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>.


===Send and receive helper functions===
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() and evaluateJavaScript() to exchange arbitrary data structures (values, lists, dictionaries) between Python and JavaScript in the WebView.


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.
== WebKitView.py ==


===Putting it all together===
=== Importing required modules ===


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()'''.
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.


==WebKitView.qml==
<code>
import sys
import time
import json


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.
from PySide import QtGui, QtDeclarative
</code>


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


===<span class="caps">HTML</span> header===
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" on the WebView object, which will rotate it in our view.


Here’s how we start out with the <span class="caps">HTML</span> file:
<code>
def sendData(data):
global rootObject
print 'Sending data:', data
json_str = json.dumps(data).replace('"', '"')
rootObject.evaluateJavaScript('receiveJSON("s")' json_str)


===JavaScript send and receive functions===
def receiveData(json_str):
global rootObject


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.
data = json.loads(json_str)
print 'Received data:', data
 
if len(data)  2 and data[0]  'setRotation':
rootObject.setProperty('rotation', data[1])
else:
sendData({'Hello': 'from PySide', 'itsNow': int(time.time())})
</code>
 
=== 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()'''.
 
<code>
app = QtGui.QApplication(sys.argv)
 
view = QtDeclarative.QDeclarativeView()
view.setRenderHints(QtGui.QPainter.SmoothPixmapTransform)
view.setSource(''file''.replace('.py', '.qml'))
rootObject = view.rootObject()
rootObject.setProperty('url', ''file''.replace('.py', '.html'))
rootObject.alert.connect(receiveData)
view.show()
 
app.exec_()
</code>
 
== WebKitView.qml ==
 
This one is relatively unspectacular. Simply import QtWebKit (for this you have to install the '''libqtwebkit-qmlwebkitplugin''' package) and create a new WebView. The '''settings.javascriptEnabled''' part here is key - without it, JavaScript inside the WebView will not be executed.
 
<code>
import QtWebKit 1.0
 
WebView { settings.javascriptEnabled: true; width: 400; height: 280 }
</code>
 
== WebKitView.html ==
 
=== HTML header ===
 
Here's how we start out with the HTML file:
 
<code>
<html>
<head>
<script language="javascript" type="text/javascript">
</code>


===Callbacks for our buttons===
=== JavaScript send and receive functions ===


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:
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.


===The <span class="caps">HTML</span> body contents===
<code>
function sendJSON(data) {
alert(JSON.stringify(data));
}
function receiveJSON(data) {
element = document.getElementById('received');
element. innerHTML ''= ""'' data;
}
</code>


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:
=== Callbacks for our buttons ===


==How the example app looks like==
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:


Once you have got all three files, start the example app like this: '''python WebKitView.py'''
<code>
function setRotation() {
element = document.getElementById('rotate');
angle = parseInt(element.value);
message = ['setRotation', angle];
sendJSON(message);
}
function sendStuff() {
sendJSON([42, 'PySide', 1.23, true, {'a':1,'b':2}]);
}
</code>


[[Image:5226208800_5a1b8351f5_z.jpg|Screenshot of WebKitView inside QML with Python]]
=== The HTML body contents ===


===Categories:===
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|Developing_with_Qt]]
<code>
** [[:Category:Developing with Qt::Qt-Quick|Qt Quick]]
</script>
* [[:Category:Developing with Qt::Qt-Quick::QML|QML]]
</head>
<body>
<h2>PySide + QML + WebKit FTW</h2>
<p>
Set rotation:
<input type="text" size="5" id="rotate" value="10"/>
<button onclick=setRotation()>Click me now!</button>
</p>
<p>
Send arbitrary data structures:
<button onclick=sendStuff()>No, click me!</button>
</p>
<p>Received stuff:</p>
<pre id="received"></pre>
</body>
</html>
</code>


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


* [[:Category:Developing with Qt::QtWebKit|QtWebKit]]
Once you have got all three files, start the example app like this: '''python WebKitView.py'''


* [[:Category:LanguageBindings|LanguageBindings]]
http://farm6.static.flickr.com/5169/5226208800_5a1b8351f5_z.jpg
** [[:Category:LanguageBindings::PySide|PySide]]
* [[:Category:snippets|snippets]]

Latest revision as of 10:33, 24 February 2022


Attention
This is a page dedicated to PySide (Qt4). For recent development on PySide2 (Qt5) and PySide6 (Qt6) refer to Qt for Python

English French


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() 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.

import sys
import time
import json

from PySide import QtGui, QtDeclarative

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" on the WebView object, which will rotate it in our view.

def sendData(data):
 global rootObject
 print 'Sending data:', data
 json_str = json.dumps(data).replace('"', '"')
 rootObject.evaluateJavaScript('receiveJSON("s")' json_str)

def receiveData(json_str):
 global rootObject

data = json.loads(json_str)
 print 'Received data:', data

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

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().

app = QtGui.QApplication(sys.argv)

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

app.exec_()

WebKitView.qml

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

import QtWebKit 1.0

WebView { settings.javascriptEnabled: true; width: 400; height: 280 }

WebKitView.html

HTML header

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

<html>
 <head>
 <script language="javascript" type="text/javascript">

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.

 function sendJSON(data) {
 alert(JSON.stringify(data));
 }
 function receiveJSON(data) {
 element = document.getElementById('received');
 element. innerHTML ''= ""'' data;
 }

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:

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

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:

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

How the example app looks like

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

5226208800_5a1b8351f5_z.jpg