Nothing like getting the feet wet: let's investigate the structure of a PyQt application by putting together the minimal set of components that can show something on screen, slowly expanding it to show more features.
A tiny PyQt applications has the following elements:
an application object
a main window (which has a central widget), or
a main widget
This is the traditional ”Hello World” button application, with as little code as possible:
Hello World
Example 6-1. hello1.py — hello world
# # hello1.py # import sysfrom qt import *
app=QApplication(sys.argv)
button=QPushButton("Hello World", None)
app.setMainWidget(button)
button.show()
app.exec_loop()
![]()
One of the niceties of Qt is that you have access to all supported widget styles on all platforms. (Except for the Aqua style - that is only available on OS X, because Apple doesn't want it to spread to other platforms.)
from qt import QApplication, QPushButton
From version 3.x of PyQt, the library has been split into several separate modules. The Qt module still gets you all the basic stuff, but more advanced functionality, such as the canvas, is divided over separate modules, qtcanvas for QCanvas, for instance.
app.setMainWidget(button)
Note: Note that this is one of the few instances where a method name differs between Python and C++: the C++ method is called exec(), which is a reserved word in Python. Except for a few cases like this, reading the C++ documentation for Python use demands little more than a simple mental substitution.
Experienced Pythoneers will also note that the parameters in PyQt function calls are positional — not by keyword. In the old Tkinter GUI toolkit most function calls take the form:
b = Button(root, text=label, command=func)where PyQt wants:
b = QPushButton(root, label, func)Just something to be aware of: keyword parameters can be added in any old order, but positional parameters have to be in the right position.