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

From Qt Wiki
Jump to navigation Jump to search
(Convert ExpressionEngine links)
(Decode HTML entity names)
Line 88: Line 88:


<code>
<code>
<html&amp;amp;gt;
<html>
  <head&amp;amp;gt;
  <head>
  <script language="javascript" type="text/javascript">
  <script language="javascript" type="text/javascript">
</code>
</code>
Line 128: Line 128:


<code>
<code>
  </script&amp;amp;gt;
  </script>
  </head&amp;amp;gt;
  </head>
  <body&amp;amp;gt;
  <body>
  <h2>PySide + QML + WebKit FTW</h2>
  <h2>PySide + QML + WebKit FTW</h2>
  <p>
  <p>
  Set rotation:
  Set rotation:
  <input type="text" size="5" id="rotate" value="10"/&amp;amp;gt;
  <input type="text" size="5" id="rotate" value="10"/>
  <button onclick=setRotation()>Click me now!</button>
  <button onclick=setRotation()>Click me now!</button>
  </p>
  </p>
Line 143: Line 143:
  <p>Received stuff:</p>
  <p>Received stuff:</p>
  <pre id="received"></pre>
  <pre id="received"></pre>
  </body&amp;amp;gt;
  </body>
</html&amp;amp;gt;
</html>
</code>
</code>



Revision as of 17:54, 12 March 2015

This article may require cleanup to meet the Qt Wiki's quality standards. Reason: Auto-imported from ExpressionEngine.
Please improve this article if you can. Remove the {{cleanup}} tag and add this page to Updated pages list after it's clean.

[toc align_right="yes" depth="3"]

English French

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

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