PyQt v4 - Python Bindings for Qt v4 | Документация
PyQt v4 - Python Bindings for Qt v4
Reference Guide
Contact: info@riverbankcomputing.com Version: 4.4.4 Copyright: Copyright (c) 2008 Riverbank Computing Limited
- 1 Introduction
- 2 Installing PyQt
- 3 Signal and Slot Support
- 4 Python Objects and QVariant
- 5 Support for Pickling
- 6 Support for Python's Buffer Interface
- 7 Using PyQt from the Python Shell
- 8 Using Qt Designer
- 9 The PyQt Resource System
- 10 Internationalisation of PyQt Applications
- 11 The DBus Support Module
- 12 Things to be Aware Of
- 13 Deploying Commercial PyQt Applications
- 14 The PyQt Build System
1 Introduction
This is the reference guide for PyQt 4.4.4. PyQt v4 is a set of
Python bindings for v4 of the Qt application
framework from Trolltech.There is a separate PyQt API Reference.
Qt is a set of C++ libraries and development tools that includes platform
independent abstractions for graphical user interfaces, networking, threads,
Unicode, regular expressions, SQL databases, SVG, OpenGL, XML, and user and
application settings. PyQt implements 440 of these classes as a set of
Python modules.PyQt supports the Windows, Linux, UNIX and MacOS/X platforms.
PyQt does not include Qt itself - you must obtain it separately.
The homepage for PyQt is http://www.riverbankcomputing.com/software/pyqt/.
Here you will always find the latest stable version, current development
snapshots, and the latest version of this documentation.PyQt is built using the SIP bindings generator. SIP must be installed in
order to build and use PyQt.Earlier versions of Qt are supported by PyQt v3.
1.1 License
Like Qt v4, PyQt is licensed on all platforms under a commercial license, the
GPL v2 and the GPL v3. Your PyQt license must be compatible with your Qt
license. If you use the GPL versions then your own code must also use a
compatible license.You can purchase a commercial PyQt license here.
1.2 PyQt Components
PyQt comprises a number of different components. First of all there are a
number of Python extension modules. These are all installed in the PyQt4
Python package.
- The QtCore module. This contains the core non-GUI classes, including
the event loop and Qt's signal and slot mechanism. It also includes
platform independent abstractions for Unicode, threads, mapped files,
shared memory, regular expressions, and user and application settings.- The QtGui module. This contains the majority of the GUI classes.
- The QtHelp module. This contains classes for creating and viewing
searchable documentation.- The QtNetwork module. This module contains classes for writing UDP
and TCP clients and servers. It includes classes that implement FTP and
HTTP clients and support DNS lookups.- The QtOpenGL module. This module contains classes that enable the
use of OpenGL in rendering 3D graphics in PyQt applications.- The QtScript module. This module contains classes that enable PyQt
applications to be scripted using Qt's JavaScript interpreter.- The QtSql module. This module contains classes that integrate with
SQL databases. It includes editable data models for database tables that
can be used with GUI classes. It also includes an implementation of
SQLite.- The QtSvg module. This module contains classes for displaying the
contents of SVG files.- The QtTest module. This module contains functions that enable unit
testing of PyQt applications. (PyQt does not implement the complete Qt
unit test framework. Instead it assumes that the standard Python unit
test framework will be used and implements those functions that simulate
a user interacting with a GUI.)- The QtWebKit module. This module implements a web browser engine
based on the WebKit open source browser engine.- The QtXml module. This module contains classes that implement SAX
and DOM interfaces to Qt's XML parser.- The QtXmlPatterns module. This module contains classes that
implement XQuery and XPath support for XML and custom data models.- The phonon module. This module contains classes that
implement a cross-platform multimedia framework that enables the use of
audio and video content in PyQt applications.- The QtAssistant module. This module contains classes that allow Qt
Assistant to be integrated with a PyQt application to provide online
help.- The QtDesigner module. This module contains classes that allow Qt
Designer to be extended using PyQt. See Writing Qt Designer Plugins
for a full description of how to do this.- The QAxContainer module. This module contains classes that allow
access to ActiveX controls and COM objects. It is only available in the
commercial version of PyQt for Windows.- The Qt module. This module consolidates the classes contained in all
of the modules described above into a single module. This has the
advantage that you don't have to worry about which underlying module
contains a particular class. It has the disadvantage that it loads the
whole of the Qt framework, thereby increasing the memory footprint of an
application. Whether you use this consolidated module, or the individual
component modules is down to personal taste.- The DBus support
module is installed as dbus.mainloop.qt. PyQt does not support Qt's
native DBus classes (which are very C++ orientated). Instead the
dbus.mainloop.qt module provides support for the Qt event loop in the
same way that the dbus.mainloop.glib included with the standard
dbus-python bindings package provides support for the GLib event
loop. The API is described in The DBus Support Module. It is only
available for PyQt for X11 and only if the dbus-python v0.80 (or
later) bindings package is installed.- The uic module. This module contains classes for handling the
.ui files created by Qt Designer that describe the whole or part of a
graphical user interface. It includes classes that load a .ui file
and render it directly, and classes that generate Python code from a
.ui file for later execution. It is covered in detail in The uic
Module.- The pyqtconfig module is an extention of the SIP build system and is
created when PyQt is configured. It encapsulates all the necessary
information about your Qt installation and makes it easier to write
installation scripts for bindings built on top of PyQt. It is covered
in detail in The PyQt Build System.PyQt also contains a number of utility programs.
- pyuic4 corresponds to the Qt uic utility. It converts GUIs
created using Qt Designer to Python code. It is covered in detail in
pyuic4.- pyrcc4 corresponds to the Qt rcc utility. It embeds arbitrary
resources (eg. icons, images, translation files) described by a resource
collection file in a Python module. It is covered in detail in
pyrcc4. (Note It will only be included if your copy of Qt includes
the XML module.)- pylupdate4 corresponds to the Qt lupdate utility. It extracts
all of the translatable strings from Python code and creates or updates
.ts translation files. These are then used by Qt Linguist to manage
the translation of those strings. It is covered in detail in
pylupdate4. (Note It will only be included if your copy of Qt
includes the XML module.)When PyQt is configured a file called PyQt4.api is generated. This can be
used by the QScintilla editor component (at
http://www.riverbankcomputing.com/software/qscintilla/) to enable the use of
auto-completion and call tips when editing PyQt code. The API file is
installed automatically if QScintilla is already installed.PyQt includes a large number of examples. These are ports to Python of many
of the C++ examples provided with Qt. They can be found in the examples
directory.Finally, PyQt contains the .sip files used by SIP to generate PyQt
itself. These can be used by developers of bindings of other Qt based class
libraries - for example PyQwt and PyQwt3D.2 Installing PyQt
2.1 Downloading SIP
SIP must be installed before building and using PyQt. You can get the latest
release of the SIP source code from
http://www.riverbankcomputing.com/software/sip/download.The SIP documentation can be found at
http://www.riverbankcomputing.com/static/Docs/sip4/sipref.html.2.2 Downloading PyQt
You can get the latest release of the GPL version of the PyQt source code from
http://www.riverbankcomputing.com/software/pyqt/download.If you are using the commercial version of PyQt then you should use the
download instructions which were sent to you when you made your purchase. You
must also download your license file.2.3 Configuring PyQt
After unpacking the source package (either a .tar.gz or a .zip file
depending on your platform) you should then check for any README files
that relate to your platform.If you are using the commercial version of PyQt then you must copy your
license file to the sip directory.You need to make sure your environment variables are set properly for your
development environment. For example, if you are using a binary distribution
of Qt on Windows then make sure you have run the qtvars.bat file. For
other platforms it is normally enough to ensure that Qt's bin directory is
on your PATH.Next you need to configure SIP by executing the configure.py script. For
example:python configure.pyThis assumes that the Python interpreter is on your path. Something like the
following may be appropriate on Windows:c:\python25\python configure.pyIf you have multiple versions of Python installed then make sure you use the
interpreter for which you wish to build PyQt for.The full set of command line options is:
--version Display the PyQt version number. -h, --help Display a help message. --confirm-license Using this confirms that you accept the terms of the PyQt license. -k, --static The PyQt modules will be built as static libraries. This is useful when
building a custom interpreter with the PyQt modules built in to the
interpreter.-r, --trace The generated PyQt modules contain additional tracing code that is enabled
using SIP's sip.settracemask() function.-u, --debug The PyQt modules will be built with debugging symbols. On Windows this
requires that a debug version of Python is installed.-w, --verbose Compiler commands and any output issued during configuration is displayed
instead of being suppressed. Use this if configure.py is having
problems to see what exactly is going wrong.-c, --concatenate The C++ source files for a Python module will be concatenated. This
results in significantly reduced compilation times. Most, but not all,
C++ compilers can handle the large files that result. It is recommended
that you use this option if you are using GCC v3.x or MSVC v7.x. See also
the --concatenate-split option.-j N, --concatenate-split=N If the --concatenate option is used to concatenate the C++ source files
then this option determines how many files are created. The default is 1.-g, --consolidate Normally each PyQt module (except for the Qt module) is linked against
the corresponding Qt library. This option creates a module called _qt
which is linked against all the required Qt libraries and the other modules
are stub modules that populate their module dictionaries from this one.
This is useful when linking against static Qt libraries to eliminate the
need to distribute the Qt libraries while minimising the memory footprint
of the PyQt modules.-e MODULE, --enable=MODULE Normally checks for all PyQt4 modules are enabled and are built if the
corresponding Qt library can be found. Using this option only those
modules specifically enabled will be checked for and built. The option may
be specified any number of times.-t PLUGIN, --plugin=PLUGIN If Qt has been built as static libraries then the static plugin PLUGIN
will be linked with the appropriate PyQt module. The option may be
specified any number of times.-q FILE, --qmake=FILE Qt's qmake program is used to determine how your Qt installation is
laid out. Normally qmake is found on your PATH. This option can
be used to specify a particular instance of qmake to use. This option
is not available on Windows.-s DIR, --dbus=DIR The dbus-python.h header file of the dbus-python package can be found
in the directory DIR/dbus.-b DIR, --bindir=DIR The pyuic4, pyrcc4 and pylupdate4 utilities will be installed
in the directory DIR.-d DIR, --destdir=DIR The PyQt Python package will be installed in the directory DIR. The
default is the Python installation's site-packages directory. If you
use this option then the PYTHONPATH environment variable must include
DIR.-p DIR, --plugin-destdir=DIR The Qt Designer plugin that manages plugins implemented in Python will be
installed in the designer subdirectory of the directory DIR.--no-designer-plugin The Qt Designer plugin will not be built. --no-sip-files The .sip files for the PyQt modules will not be installed. -v DIR, --sipdir=DIR The .sip files for the PyQt modules will be installed in the directory
DIR.-i, --vendorid The checking of signed Python interpreters using the VendorID package is
enabled. See also the --vendorid-incdir and --vendorid-libdir
options and Deploying Commercial PyQt Applications.-l DIR, --vendorid-incdir=DIR The header file of the VendorID package can be found in the directory
DIR.-m DIR, --vendorid-libdir=DIR The library of the VendorID package can be found in the directory DIR. -a, --qsci-api The PyQt4.api QScintilla API file is installed even if QScintilla does
not appear to be installed. This option is implied if the
--qsci-api-destdir option is specified.--no-qsci-api The PyQt4.api QScintilla API file is not installed even if QScintilla
does appear to be installed.-n DIR, --qsci-api-destdir=DIR The QScintilla API file will be installed in the python subdirectory of
the api` subdirectory of the directory ``DIR.2.4 Building PyQt
The next step is to build PyQt by running your platform's make command.
For example:makeThe final step is to install PyQt by running the following command:
make install(Depending on your system you may require root or administrator privileges.)
This will install the various PyQt components.
3 Signal and Slot Support
One of the key features of Qt is its use of signals and slots to communicate
between objects. Their use encourages the development of reusable components.A signal is emitted when a particular event occurs. A slot is a function (in
PyQt a slot is any Python callable). If a signal is connected to a slot
(using the QtCore.QObject.connect() method) then the slot is called when
the signal is emitted. If a signal isn't connected then nothing happens. The
code (or component) that emits the signal does not know or care if the signal
is being used.A signal may be connected to many slots.
A signal may also be connected to another signal.
A slot may be connected to many signals.
In PyQt signals are emitted using the QtCore.QObject.emit() method.
Connections may be direct (ie. synchronous) or queued (ie. asynchronous).
Connections may be made across threads.
Signals are disconnected using the QtCore.QObject.disconnect() method.
3.1 PyQt Signals and Qt Signals
Qt signals are statically defined as part of a C++ class. They are referenced
using the QtCore.SIGNAL() function. This method takes a single string
argument that is the name of the signal and its C++ signature. For example:QtCore.SIGNAL("finished(int)")The returned value is normally passed to the QtCore.QObject.connect()
method.PyQt allows new signals to be defined dynamically. The act of emitting a
PyQt signal implicitly defines it. PyQt v4 signals are also referenced using
the QtCore.SIGNAL() function.3.2 The PyQt_PyObject Signal Argument Type
It is possible to pass any Python object as a signal argument by specifying
PyQt_PyObject as the type of the argument in the signature. For example:QtCore.SIGNAL("finished(PyQt_PyObject)")While this would normally be used for passing objects like lists and
dictionaries as signal arguments, it can be used for any Python type. Its
advantage when passing, for example, an integer is that the normal conversions
from a Python object to a C++ integer and back again are not required.The reference count of the object being passed is maintained automatically.
There is no need for the emitter of a signal to keep a reference to the object
after the call to QtCore.QObject.emit(), even if a connection is queued.3.3 Short-circuit Signals
There is also a special form of a PyQt v4 signal known as a short-circuit
signal. Short-circut signals implicitly declare each argument as being of
type PyQt_PyObject.Short-circuit signals do not have a list of arguments or the surrounding
parentheses.Short-circuit signals may only be connected to slots that have been implemented
in Python. They cannot be connected to Qt slots or the Python callables that
wrap Qt slots.3.4 PyQt Slots and Qt Slots
Qt slots are statically defined as part of a C++ class. They are referenced
using the QtCore.SLOT() function. This method takes a single string
argument that is the name of the slot and its C++ signature. For example:QtCore.SLOT("done(int)")The returned value is normally passed to the QtCore.QObject.connect()
method.PyQt allows any Python callable to be used as a slot, not just Qt slots. This
is done by simply referencing the callable. Because Qt slots are implemented
as class methods they are also available as Python callables. Therefore it is
not usually necessary to use QtCore.SLOT() for Qt slots. However, doing so
is more efficient as it avoids a conversion to Python and back to C++.Qt allows a signal to be connected to a slot that requires fewer arguments than
the signal passes. The extra arguments are quietly discarded. PyQt slots can
be used in the same way.Note that when a slot is a Python callable its reference count is not
increased. This means that a class instance can be deleted without having to
explicitly disconnect any signals connected to its methods. However, if a slot
is a lambda function or a partial function then its reference count is
automatically incremented to prevent it from being immediately garbage
collected.3.5 Connecting Signals and Slots
Connections between signals and slots (and other signals) are made using the
QtCore.QObject.connect() method. For example:QtCore.QObject.connect(a, QtCore.SIGNAL("QtSig()"), pyFunction) QtCore.QObject.connect(a, QtCore.SIGNAL("QtSig()"), pyClass.pyMethod) QtCore.QObject.connect(a, QtCore.SIGNAL("QtSig()"), b, QtCore.SLOT("QtSlot()")) QtCore.QObject.connect(a, QtCore.SIGNAL("PySig()"), b, QtCore.SLOT("QtSlot()")) QtCore.QObject.connect(a, QtCore.SIGNAL("PySig"), pyFunction)Disconnecting signals works in exactly the same way using the
QtCore.QObject.disconnect() method. However, not all the variations of
that method are supported by PyQt. Signals must be disconnected one at a
time.3.6 Emitting Signals
Any instance of a class that is derived from the QtCore.QObject class can
emit a signal using its emit() method. This takes a minimum of one
argument which is the signal. Any other arguments are passed to the connected
slots as the signal arguments. For example:a.emit(QtCore.SIGNAL("clicked()")) a.emit(QtCore.SIGNAL("pySig"), "Hello", "World")3.7 The QtCore.pyqtSignature() Decorator
Many of Qt's features make use of its meta-object system. In order to make
use of these features from Python it is sometimes necessary to make certain
Python objects (i.e. QObject sub-classes, properties and methods) appear
as C++ objects. In particular it is sometimes necessary to define a C++
function signature that a Python method emulates. PyQt provides the
QtCore.pyqtSignature() function decorator to do this.The decorator takes a signature argument and an optional result
argument. Both are strings.The signature is a comma separated list of C++ types representing each of
the arguments. The list may be enclosed in (). The list may also be
preceeded by a function name. If the name is given then the () must also
be given. If the name is omitted then the name of the Python method being
decorated is used instead.The result argument is simply the C++ type of the result. If it is omitted
then it is assumed that no result is returned.For example:
@QtCore.pyqtSignature("") def foo(self): """ C++: void foo() """ @QtCore.pyqtSignature("int, char *") def foo(self, arg1, arg2): """ C++: void foo(int, char *) """ @QtCore.pyqtSignature("bar(int)") def foo(self, arg1): """ C++: void bar(int) """ @QtCore.pyqtSignature("int", result="int") def foo(self, arg1): """ C++: int foo(int) """Any method of a class that is a sub-class of QObject that is decorated is
defined to Qt's meta-object system as a slot.The following sections describe the situations that the decorator might be
used.3.7.1 Integrating Python and JavaScript in QtWebKit
QtWebKit uses slots to expose class methods implemented in C++ as JavaScript
methods that can be called from scripts embedded in HTML. Python class
methods that have been decorated behave in exactly the same way.In the same way, properties created using QtCore.pyqtProperty() are also
automatically exposed as JavaScript properties.3.7.2 Using Python Widgets in Qt Designer
Using the decorator is one part of enabling a GUI widget implemented in Python
to be used in Qt Designer in the same way as a widget implemented in C++. See
Writing Qt Designer Plugins for the details.3.7.3 Connecting Slots By Name
PyQt supports the QtCore.QMetaObject.connectSlotsByName() function that
is most commonly used by pyuic4 generated Python code to automatically
connect signals to slots that conform to a simple naming convention. However,
where a class has overloaded Qt signals (ie. with the same name but with
different arguments) PyQt needs additional information in order to
automatically connect the correct signal.For example the QtGui.QSpinBox class has the following signals:
void valueChanged(int i); void valueChanged(const QString &text);When the value of the spin box changes both of these signals will be emitted.
If you have implemented a slot called on_spinbox_valueChanged (which
assumes that you have given the QSpinBox instance the name spinbox)
then it will be connected to both variations of the signal. Therefore, when
the user changes the value, your slot will be called twice - once with an
integer argument, and once with a QString argument.This also happens with signals that take optional arguments. Qt implements
this using multiple signals. For example, QtGui.QAbstractButton has the
following signal:void clicked(bool checked = false);Qt implements this as the following:
void clicked(); void clicked(bool checked);The decorator can be used to specify which of the signals should be connected
to the slot.For example, if you were only interested in the integer variant of the signal
then your slot definition would look like the following:@QtCore.pyqtSignature("int") def on_spinbox_valueChanged(self, i): # i will be an integer. passIf you wanted to handle both variants of the signal, but with different Python
methods, then your slot definitions might look like the following:@QtCore.pyqtSignature("on_spinbox_valueChanged(int)") def spinbox_int_value(self, i): # i will be an integer. pass @QtCore.pyqtSignature("on_spinbox_valueChanged(const QString &)") def spinbox_qstring_value(self, qs): # qs will be a QString. passThe following shows an example using a button when you are not interested in
the optional argument:@QtCore.pyqtSignature("") def on_button_clicked(self): pass4 Python Objects and QVariant
Qt uses the QVariant class as a wrapper for any C++ data type. PyQt allows
any Python object to be wrapped as a QVariant and passed around Qt's
meta-object system like any other type.PyQt will try to convert the Python object to a C++ equivalent if it can so
that the QVariant can be passed to other C++ code that doesn't know what a
Python object is.PyQt provides the toPyObject() method of QVariant which will convert
the QVariant back to a Python object of the correct type. It will raise a
Python exception if it cannot do so.5 Support for Pickling
The following PyQt classes may be pickled.
- QByteArray
- QChar
- QColor
- QDate
- QDateTime
- QKeySequence
- QLatin1Char
- QLatin1String
- QLine
- QLineF
- QMatrix
- QPoint
- QPointF
- QPolygon
- QRect
- QRectF
- QSize
- QSizeF
- QString
- QTime
Also all named enums (QtCore.Qt.Key for example) may be pickled.
6 Support for Python's Buffer Interface
If SIP v4.7.5 or later is used then any Python object that supports the buffer
interface can be used whenever a char or char * is expected. If the
buffer has multiple segments then all but the first will be ignored.7 Using PyQt from the Python Shell
PyQt installs an input hook (using PyOS_InputHook) that processes events
when an interactive interpreter is waiting for user input. This means that
you can, for example, create widgets from the Python shell prompt, interact
with them, and still being able to enter other Python commands.For example, if you enter the following in the Python shell:
>>> from PyQt4 import QtGui >>> a = QtGui.QApplication([]) >>> w = QtGui.QWidget() >>> w.show() >>> w.hide() >>>The widget would be displayed when w.show() was entered amd hidden as soon
as w.hide() was entered.The installation of an input hook can cause problems for certain applications
(particularly those that implement a similar feature using different means).
The QtCore module contains the pyqtRemoveInputHook() and
pyqtRestoreInputHook() functions that remove and restore the input hook
respectively.8 Using Qt Designer
Qt Designer is the Qt tool for designing and building graphical user
interfaces. It allows you to design widgets, dialogs or complete main windows
using on-screen forms and a simple drag-and-drop interface. It has the ability
to preview your designs to ensure they work as you intended, and to allow you
to prototype them with your users, before you have to write any code.Qt Designer uses XML .ui files to store designs and does not generate any
code itself. Qt includes the uic utility that generates the C++ code that
creates the user interface. Qt also includes the QUiLoader class that
allows an application to load a .ui file and to create the corresponding
user interface dynamically.PyQt does not wrap the QUiLoader class but instead includes the uic
Python module. Like QUiLoader this module can load .ui files to create
a user interface dynamically. Like the uic utility it can also generate
the Python code that will create the user interface. PyQt's pyuic4
utility is a command line interface to the uic module. Both are described
in detail in the following sections.8.1 Using the Generated Code
The code that is generated has an identical structure to that generated by Qt's
uic and can be used in the same way.The code is structured as a single class that is derived from the Python
object type. The name of the class is the name of the toplevel object set
in Designer with Ui_ prepended. (In the C++ version the class is defined
in the Ui namespace.) We refer to this class as the form class.The class contains a method called setupUi(). This takes a single argument
which is the widget in which the user interface is created. The type of this
argument (typically QDialog, QWidget or QMainWindow) is set in
Designer. We refer to this type as the Qt base class.In the following examples we assume that a .ui file has been created
containing a dialog and the name of the QDialog object is ImageDialog.
We also assume that the name of the file containing the generated Python code
is ui_imagedialog.py. The generated code can then be used in a number of
ways.The first example shows the direct approach where we simply create a simple
application to create the dialog:import sys from PyQt4 import QtGui from ui_imagedialog import Ui_ImageDialog app = QtGui.QApplication(sys.argv) window = QtGui.QDialog() ui = Ui_ImageDialog() ui.setupUi(window) window.show() sys.exit(app.exec_())The second example shows the single inheritance approach where we sub-class
QDialog and set up the user interface in the __init__() method:from PyQt4 import QtCore, QtGui from ui_imagedialog import Ui_ImageDialog class ImageDialog(QtGui.QDialog): def __init__(self): QtGui.QDialog.__init__(self) # Set up the user interface from Designer. self.ui = Ui_ImageDialog() self.ui.setupUi(self) # Make some local modifications. self.ui.colorDepthCombo.addItem("2 colors (1 bit per pixel)") # Connect up the buttons. self.connect(self.ui.okButton, QtCore.SIGNAL("clicked()"), self, QtCore.SLOT("accept()")) self.connect(self.ui.cancelButton, QtCore.SIGNAL("clicked()"), self, QtCore.SLOT("reject()"))The third example shows the multiple inheritance approach:
from PyQt4 import QtCore, QtGui from ui_imagedialog import Ui_ImageDialog class ImageDialog(QtGui.QDialog, Ui_ImageDialog): def __init__(self): QtGui.QDialog.__init__(self) # Set up the user interface from Designer. self.setupUi(self) # Make some local modifications. self.colorDepthCombo.addItem("2 colors (1 bit per pixel)") # Connect up the buttons. self.connect(self.okButton, QtCore.SIGNAL("clicked()"), self, QtCore.SLOT("accept()")) self.connect(self.cancelButton, QtCore.SIGNAL("clicked()"), self, QtCore.SLOT("reject()"))It is also possible to use the same approach used in PyQt v3. This is shown in
the final example:from PyQt4 import QtCore, QtGui from ui_imagedialog import ImageDialog class MyImageDialog(ImageDialog): def __init__(self): ImageDialog.__init__(self) # Make some local modifications. self.colorDepthCombo.addItem("2 colors (1 bit per pixel)") # Connect up the buttons. self.connect(self.okButton, QtCore.SIGNAL("clicked()"), self, QtCore.SLOT("accept()")) self.connect(self.cancelButton, QtCore.SIGNAL("clicked()"), self, QtCore.SLOT("reject()"))For a full description see the Qt Designer Manual in the Qt Documentation.
8.2 The uic Module
The uic module contains the following functions.
- compileUi(uifile, pyfile, execute=False, indent=4, pyqt3_wrapper=False)
This function generates the Python code that will create a user interface
from a Qt Designer .ui file.uifile is a file name or file-like object containing the .ui file.
pyfile is the file-like object to which the generated Python code will
be written to.execute is optionally set if a small amount of additional code is to be
generated that will display the user interface if the code is run as a
standalone application.indent is the optional number of spaces used for indentation in the
generated code. If it is zero then a tab character is used instead.pyqt3_wrapper is optionally set if a small wrapper is to be generated
that allows the generated code to be used as it is by PyQt v3 applications.- loadUiType(uifile)
This function loads a Qt Designer .ui file and returns a tuple of the
generated form class and the Qt base class. These can then be used to
create any number of instances of the user interface without having to
parse the .ui file more than once.uifile is a file name or file-like object containing the .ui file.
- loadUi(uifile, baseinstance=None)
This function loads a Qt Designer .ui file and returns an instance of
the user interface.uifile is a file name or file-like object containing the .ui file.
baseinstance is an optional instance of the Qt base class. If
specified then the user interface is created in it. Otherwise a new
instance of the base class is automatically created.8.3 pyuic4
The pyuic4 utility is a command line interface to the uic module. The
command has the following syntax:pyuic4 [options] .ui-fileThe full set of command line options is:
-h, --help A help message is written to stdout. --version The version number is written to stdout. -i N, --indent=N The Python code is generated using an indentation of N
spaces. If N is 0 then a tab is used. The default is
4.-o FILE, --output=FILE The Python code generated is written to the file FILE. -p, --preview The GUI is created dynamically and displayed. No
Python code is generated.-w, --pyqt3-wrapper The generated Python code includes a small wrapper that
allows the GUI to be used in the same way as it is used
in PyQt v3.-x, --execute The generated Python code includes a small amount of
additional code that creates and displays the GUI when
it is executes as a standalone application.8.4 Writing Qt Designer Plugins
Qt Designer can be extended by writing plugins. Normally this is done using
C++ but PyQt also allows you to write plugins in Python. Most of the time a
plugin is used to expose a custom widget to Designer so that it appears in
Designer's widget box just like any other widget. It is possibe to change the
widget's properties and to connect its signals and slots.It is also possible to add new functionality to Designer. See the Qt
documentation for the full details. Here we will concentrate on describing
how to write custom widgets in Python.The process of integrating Python custom widgets with Designer is very similar
to that used with widget written using C++. However, there are particular
issues that have to be addressed.
- Designer needs to have a C++ plugin that conforms to the interface
defined by the QDesignerCustomWidgetInterface class. (If the plugin
exposes more than one custom widget then it must conform to the
interface defined by the QDesignerCustomWidgetCollectionInterface
class.) In addition the plugin class must sub-class QObject as well
as the interface class. PyQt does not allow Python classes to be
sub-classed from more than one Qt class.- Designer can only connect Qt signals and slots. It has no understanding
of Python signals or callables.- Designer can only edit Qt properties that represent C++ types. It has no
understanding of Python attributes or Python types.PyQt provides the following components and features to resolve these issues as
simply as possible.
PyQt's QtDesigner module includes additional classes (all of which have a
QPy prefix) that are already sub-classed from the necessary Qt
classes. This avoids the need to sub-class from more than one Qt class
in Python. For example, where a C++ custom widget plugin would sub-class
from QObject and QDesignerCustomWidgetInterface, a Python custom
widget plugin would instead sub-class from
QPyDesignerCustomWidgetPlugin.PyQt installs a C++ plugin in Designer's plugin directory. It conforms
to the interface defined by the
QDesignerCustomWidgetCollectionInterface class. It searches a
configurable set of directories looking for Python plugins that
implement a class sub-classed from QPyDesignerCustomWidgetPlugin.
Each class that is found is instantiated and the instance created is
added to the custom widget collection.The PYQTDESIGNERPATH environment variable specifies the set of
directories to search for plugins. Directory names are separated by a
path separator (a semi-colon on Windows and a colon on other platforms).
If a directory name is empty (ie. there are consecutive path separators
or a leading or trailing path separator) then a set of default
directories is automatically inserted at that point. The default
directories are the python subdirectory of each directory that
Designer searches for its own plugins. If the environment variable is
not set then only the default directories are searched. If a file's
basename does not end with plugin then it is ignored.A Python custom widget may define new Qt signals using the
__pyqtSignals__ class attribute. This should define a sequence of
strings each of which is the C++ signature (but excluding the return
type) of the signal. For example:__pyqtSignals__ = ("nameChanged(const QString &)", "failed()")A Python class method may be defined as a new Qt slot by using the
QtCore.pyqtSignature decorator. For example:# Define a Qt slot that takes a C++ integer argument. @QtCore.pyqtSignature("addToTotal(int)") def add_int_to_total(self, value): pass # Define a similar slot that takes its name from the method. @QtCore.pyqtSignature("int") def addToTotal(self, value): passA new Qt property may be defined using the QtCore.pyqtProperty()
function. It is used in the same way as the standard Python
property() function. In fact, Qt properties defined in this way
also behave as Python properties. The full signature of the function is
as follows:pyqtProperty(type, fget=None, fset=None, freset=None, fdel=None, doc=None, designable=True, scriptable=True, stored=True, user=False)type is a string that defines the C++ type of the property.
freset is a function used to reset the value of the property to its
default value.
designable sets the Qt DESIGNABLE flag.
scriptable sets the Qt SCRIPTABLE flag.
stored sets the Qt STORED flag.
user sets the Qt USER flag.The remaining arguments are the same as those used by the standard
property() function.Qt makes no use of the fdel function and Python makes no use of the
freset function, or the designable, scriptable, stored
and user flags.Note that the ability to define new Qt signals, slots and properties from
Python is potentially useful to plugins conforming to any plugin interface and
not just that used by Designer.For a simple but complete and fully documented example of a custom widget that
defines new Qt signals, slots and properties, and its plugin, look in the
examples/designer/plugins directory of the PyQt source package. The
widgets subdirectory contains the pydemo.py custom widget and the
python subdirectory contains its pydemoplugin.py plugin.9 The PyQt Resource System
PyQt supports Qt's resource system. This is a facility for embedding
resources such as icons and translation files in an application. This makes
the packaging and distribution of those resources much easier.A .qrc resource collection file is an XML file used to specify which
resource files are to be embedded. The application then refers to the resource
files by their original names but preceded by a colon.For a full description, including the format of the .qrc files, see the Qt
Resource System in the Qt documentation.9.1 pyrcc4
pyrcc4 is PyQt's equivalent to Qt's rcc utility and is used in exactly
the same way. pyrcc4 reads the .qrc file, and the resource files, and
generates a Python module that only needs to be import ed by the
application in order for those resources to be made available just as if they
were the original files.pyrcc4 will only be included if your copy of Qt includes the XML module.
10 Internationalisation of PyQt Applications
PyQt and Qt include a comprehensive set of tools for translating applications
into local languages. For a full description, see the Qt Linguist Manual in
the Qt documentation.The process of internationalising an application comprises the following
steps.
- The programmer uses pylupdate4 to create or update a .ts
translation file for each language that the application is to be
translated into. A .ts file is an XML file that contains the strings
to be translated and the corresponding translations that have already
been made. pylupdate4 can be run any number of times during
development to update the .ts files with the latest strings for
translation.- The translator uses Qt Linguist to update the .ts files with
translations of the strings.- The release manager then uses Qt's lrelease utility to convert the
.ts files to .qm files which are compact binary equivalents used
by the application. If an application cannot find an appropriate .qm
file, or a particular string hasn't been translated, then the strings
used in the original source code are used instead.- The release manage may optionally use pyrcc4 to embed the .qm
files, along with other application resources such as icons, in a Python
module. This may make packaging and distribution of the application
easier.10.1 pylupdate4
pylupdate4 is PyQt's equivalent to Qt's lupdate utility and is used in
exactly the same way. A Qt .pro project file is read that specifies the
Python source files and Qt Designer interface files from which the text that
needs to be translated is extracted. The .pro file also specifies the
.ts translation files that pylupdate4 updates (or creates if necessary)
and are subsequently used by Qt Linguist.pylupdate4 will only be included if your copy of Qt includes the XML module.
10.2 Differences Between PyQt and Qt
Qt implements internationalisation support through the QTranslator class,
and the QCoreApplication::translate(), QObject::tr() and
QObject::trUtf8() methods. Usually the tr() method is used to obtain
the correct translation of a message. The translation process uses a message
context to allow the same message to be translated differently. tr() is
actually generated by moc and uses the hardcoded class name as the context.
On the other hand, QApplication::translate() allows the context to be
explicitly stated.Unfortunately, because of the way Qt implements tr() (and trUtf8()) it
is not possible for PyQt to exactly reproduce its behaviour. The PyQt
implementation of tr() (and trUtf8()) uses the class name of the
instance as the context. The key difference, and the source of potential
problems, is that the context is determined dynamically in PyQt, but is
hardcoded in Qt. In other words, the context of a translation may change
depending on an instance's class hierarchy. For example:class A(QtCore.QObject): def hello(self): return self.tr("Hello") class B(A): pass a = A() a.hello() b = B() b.hello()In the above the message is translated by a.hello() using a context of
A, and by b.hello() using a context of B. In the equivalent C++
version the context would be A in both cases.The PyQt behaviour is unsatisfactory and may be changed in the future. It is
recommended that QCoreApplication.translate() be used in preference to
tr() (and trUtf8()). This is guaranteed to work with current and
future versions of PyQt and makes it much easier to share message files
between Python and C++ code. Below is the alternative implementation of A
that uses QCoreApplication.translate():class A(QtCore.QObject): def hello(self): return QtCore.QCoreApplication.translate("A", "Hello")11 The DBus Support Module
The DBus support module is installed as dbus.mainloop.qt and provides
support for the Qt event loop to the standard dbus-python language
bindings package. The module's API is almost identical to that of the
dbus.mainloop.glib modules that provides support for the GLib event loop.The dbus.mainloop.qt module contains the following function.
- DBusQtMainLoop(set_as_default=False)
This function returns a dbus.mainloop.NativeMainLoop object that
uses the the Qt event loop.set_as_default is set to make the main loop instance the default for
all new Connection and Bus instances. It may only be specified as a
keyword argument, and not as a positional argument.The following code fragment is all that is normally needed to set up the
standard dbus-python language bindings package to be used with PyQt:import dbus.mainloop.qt dbus.mainloop.qt.DBusQtMainLoop(set_as_default=True)12 Things to be Aware Of
12.1 Python Strings, Qt Strings and Unicode
Unicode support was added to Qt in v2.0 and to Python in v1.6. In Qt, Unicode
support is implemented using the QString class. It is important to
understand that QString instances, Python string objects and Python Unicode
objects are all different but conversions between them are automatic in almost
all cases and easy to achieve manually when needed.Whenever PyQt expects a QString as a function argument, a Python string
object or a Python Unicode object can be provided instead, and PyQt will do
the necessary conversion automatically.You may also manually convert Python string and Unicode objects to QString
instances by using the QString constructor as demonstrated in the following
code fragment:qs1 = QtCore.QString("Converted Python string object") qs2 = QtCore.QString(u"Converted Python Unicode object")In order to convert a QString to a Python string object use the Python
str() builtin. Applying str() to a null QString and an empty
QString both result in an empty Python string object.In order to convert a QString to a Python Unicode object use the Python
unicode() builtin. Applying unicode() to a null QString and an
empty QString both result in an empty Python Unicode object.QString also implements Python's buffer protocol which means that a
QString can be used in many places where a Python string or Unicode object
is expected without being explicitly converted.12.2 Garbage Collection
C++ does not garbage collect unreferenced class instances, whereas Python does.
In the following C++ fragment both colours exist even though the first can no
longer be referenced from within the program:col = new QColor(); col = new QColor();In the corresponding Python fragment, the first colour is destroyed when the
second is assigned to col:col = QtGui.QColor() col = QtGui.QColor()In Python, each colour must be assigned to different names. Typically this is
done within class definitions, so the code fragment would be something like:self.col1 = QtGui.QColor() self.col2 = QtGui.QColor()Sometimes a Qt class instance will maintain a pointer to another instance and
will eventually call the destructor of that second instance. The most common
example is that a QObject (and any of its sub-classes) keeps pointers to
its children and will automatically call their destructors. In these cases,
the corresponding Python object will also keep a reference to the corresponding
child objects.So, in the following Python fragment, the first QLabel is not destroyed
when the second is assigned to lab because the parent QWidget still has
a reference to it:parent = QtGui.QWidget() lab = QtGui.QLabel("First label", parent) lab = QtGui.QLabel("Second label", parent)12.3 Multiple Inheritance
It is not possible to define a new Python class that sub-classes from more than
one Qt class.12.4 Access to Protected Member Functions
When an instance of a C++ class is not created from Python it is not possible
to access the protected member functions, or emit any signals, of that
instance. Attempts to do so will raise a Python exception. Also, any Python
methods corresponding to the instance's virtual member functions will never be
called.12.5 None and NULL
Throughout PyQt, the None value can be specified wherever NULL is
acceptable to the underlying C++ code.Equally, NULL is converted to None whenever it is returned by the
underlying C++ code.12.6 Support for void *
PyQt (actually SIP) represents void * values as objects of type
sip.voidptr. Such values are often used to pass the addresses of external
objects between different Python modules. To make this easier, a Python
integer (or anything that Python can convert to an integer) can be used
whenever a sip.voidptr is expected.A sip.voidptr may be converted to a Python integer by using the int()
builtin function.A sip.voidptr may be converted to a Python string by using its
asstring() method. The asstring() method takes an optional integer
argument which is the length of the data in bytes.A sip.voidptr may also be given a size (ie. the size of the block of
memory that is pointed to) by calling its setsize() method. If it has a
size then it is also able to support Python's buffer protocol. This means
that it can be wrapped using Python's buffer() builtin to create an object
that treats the block of memory as a mutable list of bytes. It also means
that the Python struct module can be used to unpack and pack binary data
structures in memory, memory mapped files or shared memory.12.7 super and PyQt Classes
Internally PyQt implements a lazy technique for attribute lookup where
attributes are only placed in type and instance dictionaries when they are
first referenced. This technique is needed to reduce the time taken to import
large modules such as PyQt.In most circumstances this technique is transparent to an application. The
exception is when super is used with a PyQt class. The way that super
is currently implemented means that the lazy lookup is bypassed resulting in
AttributeError exceptions unless the attribute has been previously
referenced.Note that this restriction applies to any class wrapped by SIP and not just
PyQt.13 Deploying Commercial PyQt Applications
When deploying commercial PyQt applications it is necessary to discourage
users from accessing the underlying PyQt modules for themselves. A user that
used the modules shipped with your application to develop new applications
would themselves be considered a developer and would need their own commercial
Qt and PyQt licenses.One solution to this problem is the VendorID package. This allows
you to build Python extension modules that can only be imported by a digitally
signed custom interpreter. The package enables you to create such an
interpreter with your application embedded within it. The result is an
interpreter that can only run your application, and PyQt modules that can only
be imported by that interpreter. You can use the package to similarly restrict
access to any extension module.In order to build PyQt with support for the VendorID package, pass the -i
command line flag to configure.py.14 The PyQt Build System
The PyQt build system is an extension of the SIP build system and is
implemented by the pyqtconfig module, part of the PyQt4 package. It
can be used by configuration scripts of other bindings that build on top of
PyQt and takes care of the details of the Qt installation.The module contains a number of classes.
14.1 pyqtconfig Classes
- Configuration(sipconfig.Configuration)
This class encapsulates configuration values that can be accessed as
instance objects.The following configuration values are provided in addition to those
provided by the super-class:
- pyqt_bin_dir
- The name of the directory where the PyQt utilities are installed.
- pyqt_config_args
- The command line passed to configure.py when PyQt was
configured.- pyqt_mod_dir
- The name of the directory where the PyQt4 Python package is
installed.- pyqt_modules
- A space separated string of installed PyQt modules. The Qt
module is not included.- pyqt_sip_dir
- The name of the base directory where PyQt's .sip files are
installed. Each module's .sip files are installed in a
sub-directory with the same name as the module.- pyqt_sip_flags
- A space separated string of the sip command line arguments used
to build the PyQt modules. These should also be used when
building bindings that %Import any PyQt modules.- pyqt_version
- The PyQt version as a 3 part hexadecimal number (e.g. v4.0.1 is
represented as 0x040001).- pyqt_version_str
- The PyQt version as a string. For development snapshots it will
start with snapshot-.- qt_data_dir
- The value of QLibraryInfo::location(DataPath) for the Qt
installation.- qt_dir
- The root directory of the Qt installation (normally the directory
that contains the bin directory).- qt_edition
- The Qt edition.
- qt_framework
- Set if Qt is built as a MacOS/X framework.
- qt_inc_dir
- The value of QLibraryInfo::location(HeadersPath) for the Qt
installation.- qt_lib_dir
- The value of QLibraryInfo::location(LibrariesPath) for the Qt
installation.- qt_threaded
- Set if Qt is built with thread support (always set for PyQt).
- qt_version
- The Qt version as a 3 part hexadecimal number (e.g. v4.1.2 is
represented as 0x040102).- qt_winconfig
- Additional Windows specific configuration.
- __init__(self, sub_cfg=None)
Initialise the instance.
sub_cfg is an optional list of sub-class configurations. It should
only be used by the __init__() method of a sub-class to append its
own dictionary of configuration values before passing the list to its
super-class.- QtAssistantModuleMakefile(QtNetworkModuleMakefile)
- This class encapsulates a Makefile to build a SIP generated Python
extension module that is built on the PyQt QtAssistant module.- QAxContainerModuleMakefile(QtGuiModuleMakefile)
- This class encapsulates a Makefile to build a SIP generated Python
extension module that is built on the PyQt QAxContainer module.- QtCoreModuleMakefile(sipconfig.SIPModuleMakefile)
- This class encapsulates a Makefile to build a SIP generated Python
extension module that is built on the PyQt QtCore module.- QtHelpModuleMakefile(QtGuiModuleMakefile)
- This class encapsulates a Makefile to build a SIP generated Python
extension module that is built on the PyQt QtHelp module.- QtGuiModuleMakefile(QtCoreModuleMakefile)
- This class encapsulates a Makefile to build a SIP generated Python
extension module that is built on the PyQt QtGui module.- QtNetworkModuleMakefile(QtCoreModuleMakefile)
- This class encapsulates a Makefile to build a SIP generated Python
extension module that is built on the PyQt QtNetwork module.- QtOpenGLModuleMakefile(QtGuiModuleMakefile)
- This class encapsulates a Makefile to build a SIP generated Python
extension module that is built on the PyQt QtOpenGL module.- QtScriptModuleMakefile(QtCoreModuleMakefile)
- This class encapsulates a Makefile to build a SIP generated Python
extension module that is built on the PyQt QtScript module.- QtSqlModuleMakefile(QtGuiModuleMakefile)
- This class encapsulates a Makefile to build a SIP generated Python
extension module that is built on the PyQt QtSql module.- QtSvgModuleMakefile(QtGuiModuleMakefile)
- This class encapsulates a Makefile to build a SIP generated Python
extension module that is built on the PyQt QtSvg module.- QtTestModuleMakefile(QtCoreModuleMakefile)
- This class encapsulates a Makefile to build a SIP generated Python
extension module that is built on the PyQt QtTest module.- QtWebKitModuleMakefile(QtNetworkModuleMakefile)
- This class encapsulates a Makefile to build a SIP generated Python
extension module that is built on the PyQt QtWebKit module.- QtXmlModuleMakefile(QtCoreModuleMakefile)
- This class encapsulates a Makefile to build a SIP generated Python
extension module that is built on the PyQt QtXml module.- QtXmlPatternsModuleMakefile(QtCoreModuleMakefile)
- This class encapsulates a Makefile to build a SIP generated Python
extension module that is built on the PyQt QtXmlPatterns module.- phononModuleMakefile(QtGuiModuleMakefile)
- This class encapsulates a Makefile to build a SIP generated Python
extension module that is built on the PyQt phonon module.