1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377
|
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.
PyQt4 does not wrap the ``QUiLoader`` class but instead includes the
:mod:`~PyQt4.uic` Python module. Like ``QUiLoader`` this module can load
``.ui`` files to create a user interface dynamically. Like the :program:`uic`
utility it can also generate the Python code that will create the user
interface. PyQt4's :program:`pyuic4` utility is a command line interface to
the :mod:`~PyQt4.uic` module. Both are described in detail in the following
sections.
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 :file:`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.QtGui import QApplication, QDialog
from ui_imagedialog import Ui_ImageDialog
app = QApplication(sys.argv)
window = 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.QtGui import QDialog
from ui_imagedialog import Ui_ImageDialog
class ImageDialog(QDialog):
def __init__(self):
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.ui.okButton.clicked.connect(self.accept)
self.ui.cancelButton.clicked.connect(self.reject)
The third example shows the multiple inheritance approach::
from PyQt4.QtGui import QDialog
from ui_imagedialog import Ui_ImageDialog
class ImageDialog(QDialog, Ui_ImageDialog):
def __init__(self):
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.okButton.clicked.connect(self.accept)
self.cancelButton.clicked.connect(self.reject)
It is also possible to use the same approach used in PyQt v3. This is shown in
the final example::
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.okButton.clicked.connect(self.accept)
self.cancelButton.clicked.connect(self.reject)
For a full description see the Qt Designer Manual in the Qt Documentation.
The :mod:`~PyQt4.uic` Module
----------------------------
The :mod:`~PyQt4.uic` module contains the following functions and objects.
.. module:: PyQt4.uic
.. data:: widgetPluginPath
The list of the directories that are searched for widget plugins.
Initially it contains the name of the directory that contains the widget
plugins included with PyQt4.
.. function:: compileUi(uifile, pyfile[, execute=False[, indent=4[, pyqt3_wrapper=False[, from_imports=False[, resource_suffix='_rc']]]]])
Generate a Python module that will create a user interface from a Qt
Designer ``.ui`` file.
:param uifile:
the file name or file-like object containing the ``.ui`` file.
:param pyfile:
the file-like object to which the generated Python code will be written
to.
:param 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.
:param indent:
the optional number of spaces used for indentation in the generated
code. If it is zero then a tab character is used instead.
:param 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.
:param from_imports:
is optionally set to generate import statements that are relative to
``'.'``. At the moment this only applies to the import of resource
modules.
:resource_suffix:
is the suffix appended to the basename of any resource file specified
in the ``.ui`` file to create the name of the Python module generated
from the resource file by ``pyrcc4``. The default is ``'_rc'``, i.e.
if the ``.ui`` file specified a resource file called ``foo.qrc`` then
the corresponding Python module is ``foo_rc``.
.. function:: compileUiDir(dir[, recurse=False[, map=None[, \*\*compileUi_args]]])
Create Python modules from Qt Designer ``.ui`` files in a directory or
directory tree.
:param dir:
the name of the directory to scan for files whose name ends with
``.ui``. By default the generated Python module is created in the same
directory ending with ``.py``.
:param recurse:
is optionally set if any sub-directories should be scanned.
:param map:
an optional callable that is passed the name of the directory
containing the ``.ui`` file and the name of the Python module that will
be created. The callable should return a tuple of the name of the
directory in which the Python module will be created and the (possibly
modified) name of the module.
:param compileUi_args:
are any additional keyword arguments that are passed to
:func:`~PyQt4.uic.compileUi` that is called to create each Python
module.
.. function:: loadUiType(uifile[, from_imports=False[, resource_suffix='_rc']])
Load a Qt Designer ``.ui`` file and return 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.
:param uifile:
the file name or file-like object containing the ``.ui`` file.
:param from_imports:
is optionally set to use import statements that are relative to
``'.'``. At the moment this only applies to the import of resource
modules.
:resource_suffix:
is the suffix appended to the basename of any resource file specified
in the ``.ui`` file to create the name of the Python module generated
from the resource file by ``pyrcc4``. The default is ``'_rc'``, i.e.
if the ``.ui`` file specified a resource file called ``foo.qrc`` then
the corresponding Python module is ``foo_rc``.
:rtype:
the *form class* and the *Qt base class*.
.. function:: loadUi(uifile[, baseinstance=None[, package=''[, resource_suffix='_rc']]])
Load a Qt Designer ``.ui`` file and returns an instance of the user
interface.
:param uifile:
the file name or file-like object containing the ``.ui`` file.
:param baseinstance:
the 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.
:param package:
the optional package that is the base package for any relative imports
of custom widgets.
:resource_suffix:
is the suffix appended to the basename of any resource file specified
in the ``.ui`` file to create the name of the Python module generated
from the resource file by ``pyrcc4``. The default is ``'_rc'``, i.e.
if the ``.ui`` file specified a resource file called ``foo.qrc`` then
the corresponding Python module is ``foo_rc``.
:rtype:
the ``QWidget`` sub-class that implements the user interface.
:program:`pyuic4`
-----------------
The :program:`pyuic4` utility is a command line interface to the
:mod:`~PyQt4.uic` module. The command has the following syntax::
pyuic4 [options] .ui-file
The full set of command line options is:
.. program:: pyuic4
.. cmdoption:: -h, --help
A help message is written to ``stdout``.
.. cmdoption:: --version
The version number is written to ``stdout``.
.. cmdoption:: -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.
.. cmdoption:: -o <FILE>, --output <FILE>
The Python code generated is written to the file ``<FILE>``.
.. cmdoption:: -p, --preview
The GUI is created dynamically and displayed. No Python code is generated.
.. cmdoption:: -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.
.. cmdoption:: -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.
.. cmdoption:: --from-imports
Resource modules are imported using ``from . import`` rather than a simple
``import``.
.. cmdoption:: --resource-suffix <SUFFIX>
The suffix ``<SUFFIX>`` is appended to the basename of any resource file
specified in the ``.ui`` file to create the name of the Python module
generated from the resource file by :program:`pyrcc4`. The default is
``_rc``. For example if the ``.ui`` file specified a resource file called
``foo.qrc`` then the corresponding Python module is ``foo_rc``.
Note that code generated by :program:`pyuic4` is not guaranteed to be
compatible with earlier versions of PyQt4. However, it is guaranteed to be
compatible with later versions. If you have no control over the version of
PyQt4 the users of your application are using then you should run
:program:`pyuic4`, or call :func:`~PyQt4.uic.compileUi()`, as part of your
installation process. Another alternative would be to distribute the ``.ui``
files (perhaps as part of a resource file) and have your application load them
dynamically.
.. _ref-designer-plugins:
Writing Qt Designer Plugins
---------------------------
Qt Designer can be extended by writing plugins. Normally this is done using
C++ but PyQt4 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. PyQt4 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.
PyQt4 provides the following components and features to resolve these issues as
simply as possible.
- PyQt4'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``.
- PyQt4 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 :envvar:`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
:file:`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
:func:`~PyQt4.QtCore.pyqtSignal`.
- A Python method may be defined as a new Qt slot by using the
:func:`~PyQt4.QtCore.pyqtSlot` decorator.
- A new Qt property may be defined using the :func:`~PyQt4.QtCore.pyqtProperty`
function.
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
:file:`examples/designer/plugins` directory of the PyQt4 source package. The
:file:`widgets` subdirectory contains the :file:`pydemo.py` custom widget and
the :file:`python` subdirectory contains its :file:`pydemoplugin.py` plugin.
|