Home > Articles > Open Source > Python
Widgets used to build the GUI interface act because the source of such activities. Each PyQt widget, that is derived from QObject class, is designed to emit ‘signal’ in response to one or extra events. The signal on its own does not carry out any motion. Instead, it is ‘related’ to a ‘slot’. The slot may be any callable Python function.
␡
Page 1 of 6Next >
This chapter covers three tiny yet useful GUI applications written in PyQt and discusses PyQt's 'signals and slots' mechanism--a high-level communication mechanism for responding to user interaction that lets you ignore irrelevant detail.
This chapter is from the book
Rapid GUI Programming with Python and Qt: The Definitive Guide to PyQt Programming
This chapter is from the bookThis chapter is from the book
Rapid GUI Programming with Python and Qt: The Definitive Guide to PyQt Programming
In this chapter we begin with brief reviews of three tiny yet useful GUI applications written in PyQt. We will take the opportunity to highlight some of the issues involved in GUI programming, but we will defer most of the details to later chapters. Once we have a feel for PyQt GUI programming, we will discuss PyQt's 'signals and slots' mechanism—this is a high-level communication mechanism for responding to user interaction that allows us to ignore irrelevant detail.
Although PyQt is used commercially to build applications that vary in size from hundreds of lines of code to more than 100 000 lines of code, the applications we will build in this chapter are all less than 100 lines, and they show just how much can be done with very little code.
In this chapter we will design our user interfaces purely by writing code, but in Chapter 7, we will learn how to create user interfaces using Qt's visual design tool, Qt Designer.
Python console applications and Python module files always have a .py extension, but for Python GUI applications we use a .pyw extension. Both .py and .pyw are fine on Linux, but on Windows, .pyw ensures that Windows uses the pythonw.exe interpreter instead of python.exe, and this in turn ensures that when we execute a Python GUI application, no unnecessary console window will appear.* On Mac OS X, it is essential to use the .pyw extension.
The PyQt documentation is provided as a set of HTML files, independent of the Python documentation. The most commonly referred to documents are those covering the PyQt API. These files have been converted from the original C++/Qt documentation files, and their index page is called classes.html; Windows users will find a link to this page in their Start button's PyQt menu. It is well worth looking at this page to get an overview of what classes are available, and of course to dip in and read about those classes that seem interesting.
The first application we will look at is an unusual hybrid: a GUI application that must be launched from a console because it requires command-line arguments. We have included it because it makes it easier to explain how the PyQt event loop works (and what that is), without having to go into any other GUI details. The second and third examples are both very short but standard GUI applications. They both show the basics of how we can create and lay out widgets ('controls' in Windows-speak)—labels, buttons, comboboxes, and other on-screen elements that users can view and, in most cases, interact with. They also show how we can respond to user interactions—for example, how to call a particular function or method when the user performs a particular action.
In the last section we will cover how to handle user interactions in more depth, and in the next chapter we will cover layouts and dialogs much more thoroughly. Use this chapter to get a feel for how things work, without worrying about the details: The chapters that follow will fill in the gaps and will familiarize you with standard PyQt programming practices.
A Pop-Up Alert in 25 Lines
Our first GUI application is a bit odd. First, it must be run from the console, and second it has no 'decorations'—no title bar, no system menu, no X close button. Figure 4.1 shows the whole thing.
To get the output displayed, we could enter a command line like this:
When run, the program executes invisibly in the background, simply marking time until the specified time is reached. At that point, it pops up a window with the message text. About a minute after showing the window, the application will automatically terminate.
The specified time must use the 24-hour clock. For testing purposes we can use a time that has just gone; for example, by using 12:15 when it is really 12:30, the window will pop up immediately (well, within less than a second).
Now that we know what it does and how to run it, we will review the implementation. The file is a few lines longer than 25 lines because we have not counted comment lines and blank lines in the total—but there are only 25 lines of executable code. We will begin with the imports.
Quechan casino winterhaven california. Guests arriving by vehicle have access to free parking.If you like steakhouses, Quechan Casino Resort is conveniently located near Ironwood Steakhouse.The staff at Quechan Casino Resort looks forward to serving you during your upcoming visit. Just taking a little vacation and wanting to explore the Yuma/Winterhaven area. Decided on booking two nights at the Quechan Casino Resort as our place to stay while we did some exploration.
We import the sys module because we want to access the command-line arguments it holds in the sys.argv list. The time module is imported because we need its sleep() function, and we need the PyQt modules for the GUI and for the QTime class.
We begin by creating a QApplication object. Every PyQt GUI application must have a QApplication object. This object provides access to global-like information such as the application's directory, the screen size (and which screen the application is on, in a multihead system), and so on. This object also provides the event loop, discussed shortly.
When we create a QApplication object we pass it the command-line arguments; this is because PyQt recognizes some command-line arguments of its own, such as -geometry and -style, so we ought to give it the chance to read them. If QApplication recognizes any of the arguments, it acts on them, and removes them from the list it was given. The list of arguments that QApplication recognizes is given in the QApplication's initializer's documentation.
At the very least, the application requires a time, so we set the due variable to the time right now. We also provide a default message. If the user has not given at least one command-line argument (a time), we raise a ValueError exception. This will result in the time being now and the message being the 'usage' error message.
If the first argument does not contain a colon, a ValueError will be raised when we attempt to unpack two items from the split() call. If the hours or minutes are not a valid number, a ValueError will be raised by int(), and if the hours or minutes are out of range, due will be an invalid QTime, and we raise a ValueError ourselves. Although Python provides its own date and time classes, the PyQt date and time classes are often more convenient (and in some respects more powerful), so we tend to prefer them.
If the time is valid, we set the message to be the space-separated concatenation of the other command-line arguments if there are any; otherwise, we leave it as the default 'Alert!' that we set at the beginning. (When a program is executed on the command line, it is given a list of arguments, the first being the invoking name, and the rest being each sequence of nonwhitespace characters, that is, each 'word', entered on the command line. The words may be changed by the shell—for example, by applying wildcard expansion. Python puts the words it is actually given in the sys.argv list.)
Now we know when the message must be shown and what the message is.
We loop continuously, comparing the current time with the target time. The loop will terminate if the current time is later than the target time. We could have simply put a pass statement inside the loop, but if we did that Python would loop as quickly as possible, gobbling up processor cycles for no good reason. The time.sleep() command tells Python to suspend processing for the specified number of seconds, 20 in this case. This gives other programs more opportunity to run and makes sense since we don't want to actually do anything while we wait for the due time to arrive.
Apart from creating the QApplication object, what we have done so far is standard console programming.
We have created a QApplication object, we have a message, and the due time has arrived, so now we can begin to create our application. A GUI application needs widgets, and in this case we need a label to show the message. A QLabel can accept HTML text, so we give it an HTML string that tells it to display bold red text of size 72 points.*
In PyQt, any widget can be used as a top-level window, even a button or a label. When a widget is used like this, PyQt automatically gives it a title bar. We don't want a title bar for this application, so we set the label's window flags to those used for splash screens since they have no title bar. Once we have set up the label that will be our window, we call show() on it. At this point, the label window is not shown! The call to show() merely schedules a 'paint event', that is, it adds a new event to the QApplication object's event queue that is a request to paint the specified widget.
Next, we set up a single-shot timer. Whereas the Python library's time.sleep() function takes a number of seconds, the QTimer.singleShot() function takes a number of milliseconds. We give the singleShot() method two arguments: how long until it should time out (one minute in this case), and a function or method for it to call when it times out.
In PyQt terminology, the function or method we have given is called a 'slot', although in the PyQt documentation the terms 'callable', 'Python slot', and 'Qt slot' are used to distinguish slots from Python's __slots__, a feature of new-style classes that is described in the Python Language Reference. In this book we will use the PyQt terminology, since we never use __slots__.
So now we have two events scheduled: A paint event that wants to take place immediately, and a timer timeout event that wants to take place in a minute's time.
The call to app.exec_() starts off the QApplication object's event loop.* The first event it gets is the paint event, so the label window pops up on-screen with the given message. About one minute later the timer timeout event occurs and the QApplication.quit() method is called. This method performs a clean termination of the GUI application. It closes any open windows, frees up any resources it has acquired, and exits.
Event loops are used by all GUI applications. In pseudocode, an event loop looks like this:
When the user interacts with the application, or when certain other things occur, such as a timer timing out or the application's window being uncovered (maybe because another application was closed), an event is generated inside PyQt and added to the event queue. The application's event loop continuously checks to see whether there is an event to process, and if there is, it processes it (or passes it on to the event's associated function or method for processing).
Figure 4.2 Batch processing applications versus GUI applications
Although complete, and quite useful if you use consoles, the application uses only a single widget. Also, we have not given it any ability to respond to user interaction. It also works rather like traditional batch-processing programs. It is invoked, performs some processing (waits, then shows a message), and terminates. Most GUI programs work differently. Once invoked, they run their event loop and respond to events. Some events come from the user—for example, key presses and mouse clicks—and some from the system, for example, timers timing out and windows being revealed. They process in response to requests that are the result of events such as button clicks and menu selections, and terminate only when told to do so.
The next application we will look at is much more conventional than the one we've just seen, and is typical of many very small GUI applications generally.
Related Resources
This section describes the new style of connecting signals and slotsintroduced in PyQt4 v4.5.
One of the key features of Qt is its use of signals and slots to communicatebetween objects. Their use encourages the development of reusable components.
A signal is emitted when something of potential interest happens. A slot is aPython callable. If a signal is connected to a slot then the slot is calledwhen 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 thesignal is being used.
The signal/slot mechanism has the following features.
Unbound and Bound Signals¶Pyqt Slot
A signal (specifically an unbound signal) is an attribute of a class that is asub-class of
QObject . When a signal is referenced as an attribute of aninstance of the class then PyQt4 automatically binds the instance to the signalin order to create a bound signal. This is the same mechanism that Pythonitself uses to create bound methods from class functions.
A bound signal has
connect() , disconnect() and emit() methods thatimplement the associated functionality. It also has a signal attributethat is the signature of the signal that would be returned by Qt’s SIGNAL() macro.
A signal may be overloaded, ie. a signal with a particular name may supportmore than one signature. A signal may be indexed with a signature in order toselect the one required. A signature is a sequence of types. A type is eithera Python type object or a string that is the name of a C++ type. The name of aC++ type is automatically normalised so that, for example,
QString can beused instead of the non-normalised constQString& .
If a signal is overloaded then it will have a default that will be used if noindex is given.
When a signal is emitted then any arguments are converted to C++ types ifpossible. If an argument doesn’t have a corresponding C++ type then it iswrapped in a special C++ type that allows it to be passed around Qt’s meta-typesystem while ensuring that its reference count is properly maintained.
Defining New Signals with
|
Parameters: |
|
---|---|
Return type: |
an unbound signal
|
The following example shows the definition of a number of new signals:
New signals should only be defined in sub-classes of
QObject
. They must bepart of the class definition and cannot be dynamically added as classattributes after the class has been defined.
New signals defined in this way will be automatically added to the class’s
QMetaObject
. This means that they will appear in Qt Designer and can beintrospected using the QMetaObject
API.
Overloaded signals should be used with care when an argument has a Python typethat has no corresponding C++ type. PyQt4 uses the same internal C++ class torepresent such objects and so it is possible to have overloaded signals withdifferent Python signatures that are implemented with identical C++ signatureswith unexpected results. The following is an example of this:
Connecting, Disconnecting and Emitting Signals¶
Signals are connected to slots using the
connect()
method of a boundsignal.
connect
(slot[, type=PyQt4.QtCore.Qt.AutoConnection[, no_receiver_check=False]])¶
Connect a signal to a slot. An exception will be raised if the connectionfailed.
Parameters: |
|
---|
Signals are disconnected from slots using the
disconnect()
method of abound signal.
disconnect
([slot])¶
Disconnect one or more slots from a signal. An exception will be raised ifthe slot is not connected to the signal or if the signal has no connectionsat all.
Parameters: | slot – the optional slot to disconnect from, either a Python callable oranother bound signal. If it is omitted then all slots connected to thesignal are disconnected. |
---|
Signals are emitted from using the
emit()
method of a bound signal.
emit
(*args)¶
Emit a signal.
Parameters: | args – the optional sequence of arguments to pass to any connected slots. |
---|
The following code demonstrates the definition, connection and emit of asignal without arguments:
The following code demonstrates the connection of overloaded signals:
Connecting Signals Using Keyword Arguments¶
It is also possible to connect signals by passing a slot as a keyword argumentcorresponding to the name of the signal when creating an object, or using the
pyqtConfigure()
method of QObject
. For example the following threefragments are equivalent:
New York’s minimum gambling age varies based on the gambling option chosen. 18 year olds can participate in parimutuel wagering, the lottery, charitable gambling, and play at racinos, and some casinos. However, to play poker or gambling at the Seneca tribe’s casino requires visitors and residents to be at least 21. Minimum Age to Gamble in United States of America Below you will find the minimum legal age to gamble in various locations around the U.S., Virgin Islands and Puerto Rico. In the 50 American states, some times you'll see a variance, this usually is due to Indian casinos having different age requirements in their casinos than state regulated. Depending on which state you’re in, you could be legal for casino gambling as early as 18 years old, or you might have to wait until you’re 21.
Jan 01, 2012 Turning Stone Casino Resort. Akwesasne Mohawk Casino. Saratoga Gaming and Raceway. Batavia Downs. As far as I know all the casinos in New York are 18 to gamble except the 2 Seneca casinos.
The pyqtSlot()
Decorator¶
Although PyQt4 allows any Python callable to be used as a slot when connectingsignals, it is sometimes necessary to explicitly mark a Python method as beinga Qt slot and to provide a C++ signature for it. PyQt4 provides the
pyqtSlot()
function decorator to do this.
PyQt4.QtCore.
pyqtSlot
(types[, name[, result]])¶
Decorate a Python method to create a Qt slot.
Parameters: |
|
---|
Connecting a signal to a decorated Python method also has the advantage ofreducing the amount of memory used and is slightly faster.
For example:
It is also possible to chain the decorators in order to define a Python methodseveral times with different signatures. For example:
Connecting Slots By Name¶
PyQt4 supports the
QtCore.QMetaObject.connectSlotsByName()
function thatis most commonly used by pyuic4 generated Python code toautomatically connect signals to slots that conform to a simple namingconvention. However, where a class has overloaded Qt signals (ie. with thesame name but with different arguments) PyQt4 needs additional information inorder to automatically connect the correct signal.
For example the
QtGui.QSpinBox
class has the following signals:
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
(whichassumes that you have given the QSpinBox
instance the name spinbox
)then it will be connected to both variations of the signal. Therefore, whenthe user changes the value, your slot will be called twice - once with aninteger argument, and once with a unicode or QString
argument.
This also happens with signals that take optional arguments. Qt implementsthis using multiple signals. For example,
QtGui.QAbstractButton
has thefollowing signal:
Pyqt Signal Connect
Qt implements this as the following:
Pyqt Signal Slot
The
pyqtSlot()
decorator can be used to specify which ofthe signals should be connected to the slot.
For example, if you were only interested in the integer variant of the signalthen your slot definition would look like the following:
If you wanted to handle both variants of the signal, but with different Pythonmethods, then your slot definitions might look like the following:
The following shows an example using a button when you are not interested inthe optional argument:
Mixing New-style and Old-style Connections¶
The implementation of new-style connections is slightly different to theimplementation of old-style connections. An application can freely use bothstyles subject to the restriction that any individual new-style connectionshould only be disconnected using the new style. Similarly any individualold-style connection should only be disconnected using the old style.
Pyqt Signal Disconnect
You should also be aware that pyuic4 generates code that usesold-style connections.
Comments are closed.
Author
Write something about yourself. No need to be fancy, just an overview.