HomePython Page 3 - PyQT: Handling Windows and Buttons
QPushButton - Python
In this article, you will continue to learn about the process of building a GUI in PyQT. Specifically, you will learn about QDialog and QPushButton, which handle windows and buttons, the building blocks of most GUIs.
QPushButton provides a command button or, put more simply, a button. Typical buttons are OK, Cancel, Help, and so on. A QPushButton object can be obtained by calling the constructor with at least two parameters: the parent widget and the label to be displayed. For example, to create an object of QPushButton with the label "Test" and with the no parent widget, the statement would be:
test = QPushButton(None,"&Test")
An ampersand in front of the label marks it as an accelerator key. Or in other words, the letter succeeding the ampersand becomes a hotkey. In the above example, "T" has become a hotkey.
QPushButton can also display an icon or a pixmap. The icon has to be passed to the QPushButton as a parameter of the constructor, or as a parameter to the setPixmap() or setIconSet() methods of QPushButton class. To make it more clear, take a look at the following example:
The setIconSet() method requires an object of QPixmap, which in turn takes the name of the graphics file as a parameter. Using the setIconSet() method the icon can be manipulated.
The next aspect of QPushButton that you need to understand is the events that it can generate, in other words, the signals emitted by QPushButton. QPushButton emits three signals, which are clicked(), pressed(), and released(). Of these, clicked() signal is the most commonly used. The reason for this is that pressed and released together form the click. And most of the time the user expects processing to be done.
The clicked() signal is emitted when the button is activated. Activation means the button is pressed and released. It is also emitted when the accelerator key is pressed. The pressed() signal is emitted when the button is just pressed, while the released() signal is emitted when a pressed button is released.
Though all of these are basic events of button widgets, sometimes, capturing the wrong event/signal can be really problematic. For example, if the accept() slot of QDialog is connected with the pressed signal of QPushButton and also with the clicked(), then the clicked()-accept() connection would over-ride the pressed()-accept() connection. So this must to be kept in mind when connecting signals with slots.
That brings us to the end of our introduction. In the next section I will put the signals of QPushButton to use in order to demonstrate them in the real world.