Updating-QML-content-from-Python-threads
Updating QML content from Python threads
This PySide tutorial shows you how to use native Python threads (non-QThread, i.e. threading.Thread) to carry out work in the background (e.g. downloading files). In the special case of downloading, you might want to use QNetworkAccessManager and friends, but in this case, we assume that you can’t use it for whatever reason (e.g. because you want to use Twisted or because you already have your special download code that you want to reuse).
WorkingOnIt.py
Importing required modules
We will be using standard Python modules for threading (threading) and for downloading (urllib). From PySide, we need the standard module QtCore, QtGui and QtDeclarative:
The Downloader object
We now subclass QObject (so we can have Signals, Slots and Properties in our downloader) and implement all the properties that we need for downloading the file and also for displaying the current status in the UI:
Creating a new Downloader instance
As an example, we create a new Downloader here that downloads a kernel image for the N900 from the MeeGo repository:
QApplication, QDeclarativeView and context properties
As usual, we simply instantiate a new QApplication and a QDeclarativeView. Our Downloader is exposed to the QML context by setting it as context property downloader on the rootContext of our view. We then simply load the QML file via setSource, show the view and execute the application:
WorkingOnIt.qml
This is the QML UI for our downloader example. The interesting parts here are:
- When the button is clicked, downloader.start_download() (a PySide Slot) is called, which starts the thread
- The UI elements use properties of the downloader to determine visiblity and content – they are automatically updated when the properties are notified to be updated
How the example app looks
Save the files WorkingOnIt.py and WorkingOnIt.qml in the same folder and start the app using python WorkingOnIt.py:
Screenshot of the application in action