Please note that as of October 24, 2014, the Nokia Developer Wiki will no longer be accepting user contributions, including new entries, edits and comments, as we begin transitioning to our new home, in the Windows Phone Development Wiki. We plan to move over the majority of the existing entries. Thanks for all your past and future contributions.

Python Harness for QML

From Wiki
Jump to: navigation, search
Article Metadata
Created: rmerren (30 Nov 2010)
Last edited: hamishwillee (24 Jul 2012)

Sure you can write complete programs in QML, but how do you run them? You can always run them with the qmlviewer application for testing, but if you want something without the qmlviewer menus (and without having to crack open a C++ compiler) you can harness the qml in Python. There are two options for binding Python with Qt: PyQt4 and PySide. In this example we are using PySide[1]. (Note: You will need to have Python and Pyside and Qt all correctly installed for this to work--installation may vary depending on your system.)

If you have a QML file called MyQmlApp.qml and you want the window title to be My QML Application, then save the following code in a file called

#!/usr/bin/env python
# If QML_FILE_NAME is None, the QML file must
# have the same name as this Python script, just with
# .qml as extension instead of .py. You can override
# this by setting an explicit filename here.
WINDOW_TITLE = "My QML Application"
from PySide.QtCore import *
from PySide.QtGui import *
from PySide.QtDeclarative import *
import sys
if __name__ == '__main__':
app = QApplication(sys.argv)
f = QDeclarativeView()
f.setSource(QML_FILE_NAME or __file__.replace('.py', '.qml'))

You can change the QML_FILE_NAME and WINDOW_TITLE values (and the file name, of course) to whatever you like. Executing the file with Python will show your QML application in a clean window with no extraneous menus and with your chosen window title.

Alternative: EasyQML

This module provides even more abstraction and allows you to set context properties easily by subclassing easyqml.App:

import sys
import os
from PySide.QtCore import *
from PySide.QtGui import *
from PySide.QtDeclarative import *
def run(index_qml, vars={}, title=None):
app = QApplication(sys.argv)
view = QDeclarativeView()
rc = view.rootContext()
for key, value in vars.items():
rc.setContextProperty(key, value)
view.setWindowTitle(title or os.path.basename(index_qml))
class App(object):
def run(cls, filename=None):
if filename is None:
filename = cls.__name__ + '.qml'
run(filename, cls.__dict__, cls.__doc__ or cls.__name__)


import easyqml
class hiwelt(easyqml.App):
greeting = 'Hello World'


import Qt 4.7
Rectangle {
width: 100
height: 200
Text {
text: greeting
anchors.centerIn: parent
This page was last modified on 24 July 2012, at 02:04.
65 page views in the last 30 days.