Python Graphical User Interface
Buttons are the heartbeat of any interactive application and mastering button widgets in Qt Designer unlocks the full potential of user engagement. From triggering actions with a single click to controlling complex workflows, button widgets provide the gateway to seamless interaction. Whether you are crafting a minimalist interface or a feature rich app, understanding how to effectively use and customize button widgets in Qt Designer can transform your application into a responsive, intuitive experience that keeps users coming back. Dive in and discover how these simple yet powerful tools can make your app stand out.
Table of Content
- Introduction
- Push button
- Important properties
- Auto default
- Default
- Flat
- Important methods
- Important signals
2. Tool Button
- Important properties
- Pop-up mode
- Tool button style
- Auto raise
- Arrow type
- Important methods
- Important signals
3. Radio button
- Important properties
- Important methods
- Important signals
4. Check box
- Important properties
5. Tri-state
- Important methods
- Important signals
- Command link button
- Important properties
- Important methods
6. Set Description
- Important signals
- Dialog button box
- Important properties
- Orientation
- Standard buttons
7. Center Buttons
- Important methods
- Important signals
8. Common properties for button widgets
- Object name
- Enabled
- Geometry
- Size policy
- Minimum size
- Size increment
- Base size
- Palette
- Font
- Cursor
- Mouse Tracking
- Tablet tracking
- Focus policy
- Context menu policy
- Accept drops
- Tool tip
- Tool tip duration
- Status tip
- What’s this
- Accessible description
- Layout direction
- Auto fill Background
- Style sheet
- Locale
- Input method hints
- Text
- Icon
- Icon size
- Shortcut
- Checkable
- Checked
- Auto report
- Auto exclusive
- Auto repeat delay
- Auto repeat interval
Introduction
In this section, we shall see our next anticipated topic for
discussion, revolving around Button widgets in Qt Designer.
The different buttons present in Qt designer include Push
Button, Tool Button, Radio Button, Check Box, Command Link Button
and Dialog Button Box. We will be discussing all these widgets
in detail, including their description, importance and useful
properties, methods/functions and signals with examples.
Our entire flow of discussion will not only be restricted to this
section and the same pattern will be followed in the
explanation of other widgets of Qt Designer in the remaining
sections. All these button types will be available, as shown
in the figure 1.1 in the Widget Box where the user
can select any of the widgets under button types of Qt
Designer and drag and drop in a GUI form.
Now, without any further delay, let us learn about different
button widgets. These button widgets will come into handy
when the user wants to interact with the GUI form widgets
and waits for some kind of feedback. Icons or text can be
displayed in PyQt5 using these Button widgets. The base
class for Button widgets is QAbstractButton which provides
checkable (toggle) buttons and Push Buttons support.
Push Button
One of the most used widgets in PyQt5 without which we
cannot imagine creating an application, is none other than a
simple Button which is the Push Button. QPushButton class
which represents a Button is imported from PyQt5. QtWidgets
module. We have seen different buttons in various
applications such as OK, Cancel, Yes, No, Help and so on.
Generally, we can display simple text to the user or any icon
using a Push Button. Its shape is rectangular. Just remember,
whenever we need to prompt some action to be done in the
background of application using some click operation, the
first widget which comes to your mind must be the Push
Button.
Important Properties
There are multiple properties that will be discussed. Just drag
and drop a simple Push Button from Widget Box. Under
Property Editor, we will see different properties which are
headed under QObject, QWidget, QAbstractButton and QPushButton.
For all Qt objects, QObject class is the base class. Under this, we have the objectName property where some name is
provided by the user. The name may be changed based on
the requirement.
Apart from the properties of these 3 classes, there are some
other properties of the QPushButton widget as can be seen in
the following Figure 1.2.
(QObject, QWidget and QAbstractButton)
Auto Default
This property will enable the autoDefault Button property in a
QPushButton widget. If the parent is QDialog for buttons then
this property default value is True. Otherwise, it is False.
Auto default button may have a larger size as it is drawn
with some extra frames of 3 pixels or more.
Default
From this property, we can decide whether QPushButton widget
has a default Button property or not. It is disabled by default.
When the user presses Enter button from keyboard, the
dialog’s default button will automatically be pressed when this property will be enabled, that is, set to True but with an exception. If the autoDefault button is present and has focus,
then this autoDefault button is pressed. If there is an
autodefault button but no default button, then pressing Enter
will press an autodefault button that has focus. If no button
has focus then pressing Enter will press the next autodefault
button in the focus chain. We can see the behavior of the
default button only in dialogs. From the keyboard, we can use
a spacebar for clicking buttons when it has focus. If the
property is set to False on the current default button, then a
new default button will be automatically assigned the next
time the QPushButton widget in the dialog will receive focus.
Flat
This property will decide whether to raise the button border
or not. It is unchecked by default. Unless the button is
pressed, most styles will not paint the background when
checked.
Important Methods
Some important methods of QPushButton widget are as follows:
- isChecked(): Using this method, we will get the QPushButton
widget Boolean state. - setCheckable(): Using this method, we can distinguish the
pressed and released state of the QPushButton widget
when set to True. - text(): Using this method, we will get the text from the
QPushButton widget. - setText(): Using this method, the text will be assigned to
the QPushButton widget. - setDefault(): Using this method, the QPushButton widget
will be set as default. - setIcon(): Using this method, an icon will be assigned to
the QPushButton widget. - setEnabled(): On using this method, if set to False, the
signal will not be emitted from the QPushButton widget as
it will be disabled. - toggle(): From this method, there will be a change of
state in the QPushButton widget as it will toggle between
checkable states.
Important Signals
The signals which can be used with this QPushButton widget,
are shown in the figure below.
- pressed(): This signal will be emitted when the left
mouse button in the QPushButton widget is pressed. - released(): This signal will be emitted when the left
mouse button in the QPushButton widget is released. - clicked(): This signal will be emitted when the QPushButton
widget is clicked. - toggled(): This signal will be emitted when the QPushButton
widget state is changed.
Now, we shall see an example of the QPushButton widget where
we see its usage of properties, methods and signals.
In this code, we are discussing 5 different cases of QPushButton
widgets.
Consider the following code of run_pushbutton_eg1.py.
import sys
from PyQt5.QtWidgets import QMainWindow,
QApplication # QPBEG1_1
from pushbutton_eg1 import * # QPBEG1_2
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QPixmap,QIcon# QPBEG1_3
class MyPushButton_Example(QMainWindow):
def __init__(self):
super().__init__()
self.myui = Ui_Form()
self.myui.setupUi(self)
# Case1
self.myui.btn_checkable.setCheckable(True)
# QPBEG1_4
self.myui.btn_checkable.toggle()# QPBEG1_5
self.myui.btn_checkable.clicked.connect(self.case1)
# QPBEG1_6
# Case2
self.myui.btn_displaytxt.clicked.connect(lambda:
self.case2(self.myui.btn_displaytxt))# QPBEG1_7
# Case3
self.myui.btn_display_icon.clicked.connect(self.cas
e3)# QPBEG1_8
# Case4
self.myui.btn_default_set.setDefault(True)#
QPBEG1_9
# Case5
self.myui.btn_enable.clicked.connect(self.case5_1)#
QPBEG1_10
self.myui.btn_disable.clicked.connect(self.case5_2)
# QPBEG1_11
self.show()
def case1(self):
if self.myui.btn_checkable.isChecked():#
QPBEG1_12
self.myui.mylbl1.setText("I am
checked")
else:
self.myui.mylbl1.setText("I am
unchecked")
def case2(self, mybtn):
self.myui.mylbl2.setText("Text name is: " +
mybtn.text())# QPBEG1_13
def case3(self):
display_icon_image =
"E:/my_pythonbook/PyQt5/Chapter_4/Push_Button/help-
contents copy.png"# QPBEG1_14
try:
with open(display_icon_image):
self.myui.btn_display_icon.setIcon(QIcon(QPixmap(di
splay_icon_image)))# QPBEG1_15
self.myui.mylbl3.setPixmap(QPixmap(display_icon_ima
ge))
except FileNotFoundError:
print("Wrong image selection")
def case5_1(self):
self.myui.btn_myself.setEnabled(True)#
QPBEG1_16
def case5_2(self):
self.myui.btn_myself.setEnabled(False)#
QPBEG1_17
if __name__ == '__main__':
myapp = QApplication(sys.argv)
mywindow = MyPushButton_Example()# QPBEG1_18
sys.exit(myapp.exec_())
Output:
The output here can be seen in the multiple
scenarios.
Case 1:
When Checkable Button is clicked, there will be display of “I am
unchecked” message in the QLabel widget as shown in figure
1.7.
button is clicked
On clicking of Checkable Button again, there will be a display of
“I am checked” message in the QLabel widget as shown in
Figure 1.8.
button is clicked again
Case-2
When Display Text Button is clicked, there will be a display of
Text name is Display text message in the QLabel widget.
Case 3
When you click the Display Icon Button, the icon will be
displayed in both the button and label widget.
Case 4
Default Set on Loading Button is focused on loading of GUI, as
shown in the following figure 1.21.
Case 5
On clicking button with text Disabling, Button with text Myself
will be disabled, as shown in the following figure 1.22.
button is clicked
On clicking the button with text Enabling , Button with text Myself
will be enabled, as shown in the following Figure 1.23.
button is clicked
Let us understand important steps in the code:
- In QPBEG1_1, after importing the sys module for accessing
the command line arguments, we are importing from
the class which creates desktop-style UIs of PyQt5
package, that is, QtWidgets, QMainWindow for providing a
framework for creating new GUI interfaces and an
application handler, that is, QApplication. - In QPBEG1_2, from pushbutton_eg1.py Python file, we are
importing all the members of a module. - In QPBEG1_3, from the PyQt5 package, we are importing
from the class which contains graphical controls, that
is, QtGui, QPixMap which provides the image’s off-screen representation and QIcon class for the display of either small, large, active or disabled pixmaps from the set of
pixmaps. - In QPBEG1_4 and QPBEG1_5, our aim is to convert the
btn_checkableQPushButton widget into a toggle button. So,
first, we are setting the checkable state of this button
widget to True for distinguishing its pressed and
released state and then we are enabling this button
widget for toggling. - In QPBEG1_6, when btn_checkable button is clicked Click
event or signal Case 1 slot will be invoked. - In QPBEG1_7, when btn_displaytxt button is clicked Click
event or signal Case 2 slot will be invoked by passing
the argument as the btn_displaytxtQPushButton widget. - In QPBEG1_8, when the btn_display_icon button is clicked
Click event or signal Case 3 slot will be invoked. - In QPBEG1_9, the QPushButton widget btn_default_set will be
set as default. That is why we can see in all the cases,
that it is focusing on the QPushButton widget. The same
can be exclusively seen in the output of Case 4 which
is highlighted in a rectangular box. - In QPBEG1_10, when btn_enable button is clicked Click event or signal case5_1 slot will be invoked.
- In QPBEG1_11, when btn_disable button is clicked Click
event or signal case_2 slot will be invoked. - In QPBEG1_12, from the Case 1 method, we can identify
using is Checked() method whether btn_checkable QPushButton
widget will be pressed or released. Initially, this
btn_checkable widget is checked. So, when clicked first,
this button widget will toggle from checked to
unchecked state and the message I am unchecked will be
displayed. On clicking again, the message I am checked
will be displayed. - In QPBEG1_13, we are setting the text of the mylbl2 widget
with the text of btn_displayQPushButton widget text which
is “Displaytext”. So, on clicking the btn_display button, we
will get the message in the mylbl2 widget as the Text
name is Display text. - In QPBEG1_14, we are storing the path of the .png
extension file in an object variable display_icon_image. The path may be changed in your file system. You can
write as per need. - In QPBEG1_15, the icon will be displayed in btn_display_icon
and mylbl3 widgets after clicking the btn_display_icon
button using the setIcon() method where an icon will be
displayed as it will take QPixmap object as an argument
for any image file. Also, using the setPixmap method, we
are displaying an icon in the QLabel widget object too. - In QPBEG1_16, on clicking btn_enable button, btn_myself
button object will be set as enabled as we are using
setEnabled() method and the argument passed is True. - In QPBEG1_17, on clicking btn_disable button, btn_myself
button objects will be set as disabled as we are using
setEnabled() method and argument passed is False. - In QPBEG1_18, an instance of MyPushButton_Example class
mywindow is created.
The concept of the QPushButton widget should be clear by now.
We shall see our next widget which is the tool button widget.
Tool Button
Often, there comes a requirement for selecting commands or
actions by providing quick access buttons. In such cases, we
will be using Tool Buttons which are most commonly used in
the QToolBar widget. We generally see an icon itself instead of
text in a Tool Button widget.
Important Properties
Apart from the properties of 3 classes QObject, QWidget and
QAbstractButton, there are some other properties of the
QToolButton widget and they are explained as follows.
Designer
Using this property, a menu containing a menu set or some
action list will be described as well as how it will pop up for
Tool Buttons. There are 3 constants.
- DelayedPopup: Here, the menu will be displayed on
first pressing and then holding the Tool Button widget
down for some time duration. One of the common
examples we see is the usage of the back button in the
web browser where a menu depicting the current
history list will be displayed, if the user will press and
then hold the button down. This is the default value to
be displayed. - MenuButtonPopup: If we use this constantly, then a
special arrow is displayed in the Tool Button widget
indicating that a menu is present and will be displayed
on pressing the arrow part of the button. - InstantPopup: If we use this constantly, then the
menu will be displayed instantly with no delay on
pressing the Tool Button widget.
in Qt Designer
This property of the QToolButton widget will decide what to
display on the Tool Button, whether text only or icon only or
text beside the icon or text below the icon. We can see that
the default value is ToolButtonIconOnly. If there is a
requirement to follow the system settings, then set the
above property with ToolButtonFollowStyle. The rest of the
selections are self-explanatory.
Designer
Using this property, we can enable the autoRaise. It is
disabled by default.
ArrowType
Designer
On using this property, there is a choice available for the
user whether to display an arrow instead of an icon.
Important Methods
- setAutoRaise(): Using this method, we can check or
uncheck the autoRaise feature of QToolButton widget. - setPopupMode(): Using this method, we can describe the
popup menu way with the QToolButton widget. - setToolButtonStyle(): Using this method, we can set the
display style of the QToolButton widget, that is, whether
to display either text only or icon only or text beside
the icon or text below the icon. - setMenu(): Using this method, based on the QToolButton
widget’s popup Mode, the given menu can be
associated with the QToolButton widget.
Important Signals
The signals are similar to the QPushButton widget. In addition to
it, we have triggered signal which will be fired only if we add
some QActionconnected to the QToolButton widget using addAction()
method, that is, when action is triggered, signal will be
emitted.
This QToolButton widget is widely seen in day/today various
applications like creating a Notepad, Wordpad, Paint and so
on.
Let us create one simple application to understand this
QToolButton widget.
The Qt Designer file toolbutton_eg1.ui is shown in the following
figure.
In this code, we are discussing 8 different cases of QToolButton
widgets. The Action Editor of the above designer file is
shown in the following figure 1.31.
Consider the following code of run_toolbutton_eg1.py.
import sys
from PyQt5.QtWidgets import QMainWindow,
QApplication, QAction, QToolButton# QTBEG1_1
from toolbutton_eg1 import *# QTBEG1_2
from PyQt5 import QtGui, QtCore
from PyQt5.QtCore import Qt
class MyToolButton_Example(QMainWindow):
def __init__(self):
super().__init__()
self.myui = Ui_MainWindow()
self.myui.setupUi(self)
# Case-1
self.myui.actionNew_2.setCheckable(True) #
QTBEG1_3
self.myui.actionNew_2.setStatusTip("New
text will be displayed")# QTBEG1_4
# Case-2
self.myui.actionEdit.setCheckable(False)#
QTBEG1_5
self.myui.actionEdit.setStatusTip("Edit
text will be displayed")# QTBEG1_6
# Case-3
self.myui.actionSave_2.setStatusTip("Save
text will be displayed")# QTBEG1_7
# Case-4
self.myui.actionQuestion.setStatusTip("Question
text will be displayed")# QTBEG1_8
# addition of one toolButton using code
# Case-5
self.mytb_btn1 =
QAction(QtGui.QIcon("C:/Users/SAURABH/Desktop/pytho
n course/search.gif"),"Search",self)# QTBEG1_9
self.mytb_btn1.setStatusTip("Search text
will be displayed")# QTBEG1_10
self.myui.toolBar.addAction(self.mytb_btn1)#
QTBEG1_11
self.myui.toolBar.actionTriggered[QAction].connect(
self.mydisplay)# QTBEG1_12
# Case-6
self.mytb_btn2 = QToolButton()# QTBEG1_13
self.mytb_btn2.setCheckable(True)#
QTBEG1_14
self.mytb_btn2.setChecked(False)# QTBEG1_15
self.mytb_btn2.setArrowType(Qt.LeftArrow)#
QTBEG1_16
self.mytb_btn2.setAutoRaise(True)#
QTBEG1_17
self.mytb_btn2.setToolButtonStyle(Qt.ToolButtonIcon
Only)# QTBEG1_18
self.mytb_btn2.clicked.connect(self.myshowDetail)#
QTBEG1_19
self.myui.toolBar.addWidget(self.mytb_btn2)#
QTBEG1_20
# Case-7
self.mytb_btn3 = QToolButton()# QTBEG1_21
self.mytb_btn3.setIcon(QtGui.QIcon("C:/Users/SAURAB
H/Desktop/python course/globe-green.png")) #
QTBEG1_22
self.mytb_btn3.setIconSize(QtCore.QSize(30,30))#
QTBEG1_23
self.mytb_btn3.setPopupMode(QToolButton.MenuButtonP
opup)# QTBEG1_24
self.myui.toolBar.addWidget(self.mytb_btn3)#
QTBEG1_25
# Case-8
self.myui.actionExit.triggered.connect(self.exit)#
QTBEG1_26
self.show()
def mydisplay(self, mytxt):# QTBEG1_27
self.myui.lineEdit.setText(mytxt.text())#
QTBEG1_28
def exit(self):
sys.exit()# QTBEG1_29
def myshowDetail(self):
if self.mytb_btn2.isChecked(): # QTBEG1_30
self.myui.lineEdit.setText("Display...1")
else:
self.myui.lineEdit.setText("Display...2")#
QTBEG1_31
if __name__ == '__main__':
myapp = QApplication(sys.argv)
mywindow = MyToolButton_Example()# QTBEG1_32
sys.exit(myapp.exec_())
Output:
The output here can be seen in multiple scenarios.
Case 1
On clicking New QAction icon or pressing
Ctrl+N. Refer to the following figure where Toolbutton image icon
“New” is being clicked.
Case 2
On clicking EditQAction icon or pressing
Ctrl+E. Refer to the following figure where Toolbutton image icon
“Edit (T)” is being clicked.
Case 3
On clicking Save QAction icon or pressing
Ctrl+S.
Refer to the following figure where Toolbutton image icon
“Save” is being clicked.
Case 4
On clicking Question QAction icon.
Refer to the following figure where Toolbutton image icon
“Question (?)” is being clicked.
Case 5
On clicking ExitQAction icon
This will exit the entire application on clicking the Toolbutton
image icon “Quit”.
Case 6
On clicking Search QAction Icon
Refer to the following figure where where Toolbutton image
icon “Search” is being clicked.
Case 7
On clicking Left Arrow QToolButton.
Refer to the following figure. When left arrow QToolButton is clicked first time.
icon with arrow is clicked first time
When left arrow QToolButton is clicked next time.
icon with arrow is clicked next time
- In QTBEG1_1, after importing the sys module for accessing
the command line arguments, we are importing from
class which creates desktop style UIs of PyQt5
package, that is, QtWidgets, QMainWindow, an application
handler, that is, QApplication, QAction class for describing
abstract user interfaces and QToolButton widget. - In QTBEG1_2, from toolbutton_eg1.py Python file, we are
importing all the members of a module. - In QTBEG1_3, we are making actionNew_2 to be checkable
using setCheckable() method. That is why you need to
just observe the icon when pressed as seen in Case-1. - In QTBEG1_4, we are setting the text by the user as “New
text will be displayed” for providing the information about
actionNew_2 QAction object. - In QTBEG1_5, we are making actionEdit as non-checkable
using setCheckable() method. That is why you need to
just observe the icon when pressed, as seen in Case-2. This is done to explain the difference between icons of
first 2 cases. - In QTBEG1_6, we are setting the text by the user as “Edit
text will be displayed” for providing the information about
actionEditQAction object. - In QTBEG1_11, mytb_btn1QAction object will be added to the
toolbar using addAction() method. - In QTBEG1_12, when any icon in the toolbar will be
clicked, then actionTriggered signal will be emitted and is
connected to the method mydisplay()as seen in Case 6. - In QTBEG1_13, an instance of QToolButton object mytb_btn2 is
created. - In QTBEG1_14, we are setting the checkable property to
True using setCheckable() method of mytb_btn2 object. - In QTBEG1_15, initially mytb_btn2 object is unchecked.
- In QTBEG1_16, we are displaying an arrow as LeftArrow for
mytb_btn2 object. - In QTBEG1_17, the autoRaise property is set as True for
mytb_btn2 object. - In QTBEG1_18, the display style of QToolButton mytb_btn2
object is set as ToolButtonIconOnly. - In QTBEG1_19, when mytb_btn2 object is clicked click event or
signal myshowDetail slot will be invoked. - In QTBEG1_20, we are adding the mytb_btn2 object into the
toolbar using addWidget() method. - In QTBEG1_21, an instance of QToolButton object mytb_btn3 is
created. - In QTBEG1_22, we are adding an icon to mytb_btn3 object.
- In QTBEG1_23, the size of an icon is set as with width and
height both set as 30,30. - In QTBEG1_24, the popup menu way with mytb_btn3 object is
described as Menu ButtonPopup. Just observe in Case-8. - In QTBEG1_26, we are closing an application when
triggered signal is emitted when actionExitQAction object
is clicked as seen in Case 5. - In QTBEG1_27, mydisplay() method contains an additional
parameter as mytxt. - In QTBEG1_28, we are displaying the text of QAction object
when clicked on the toolbar into the QLineEdit widget.
We can observe the output from Cases 1,2,3,4 and 6.
Also, using shortcuts, the text can be displayed for
Case 1,2 and 3. - In QTBEG1_29, we are closing an application and will be
executed when action ExitQAction object is clicked. - In QTBEG1_30, we are checking whether mytb_btn2 object is
checked or not. - In QTBEG1_31, Display…1 will be first displayed and then
Display…2 on the input widget as initially we are first
checking and then unchecking. Observe the output in
Case 7. - In QTBEG1_32, an instance of MyToolButton_Example class
mywindow is created.
Radio Button
This widget will mainly be used when we need to select only
one option from multiple options of a GUI form. We can
provide some text label with any selectable button. If any of
the QRadioButton widget is selected, then there will be
deselection of the previously selected button since it is auto
exclusive by default. We mostly used the above widget with
QButtonGroup or QGroupBox.
Important Properties
It contains properties of 3 classes.
- QObject
- QWidget
- QAbstractButton
Important Methods
- isChecked(): Using this method, Boolean value will be
returned if the QRadioButton widget is selected. - setChecked(): Using this method, we can select/deselect
the QRadioButton widget based on the Boolean value
passed. - text(): Using this method, we can retrieve the text of
QRadioButton widget. - setIcon(): Using this method, an icon will be displayed
with QRadioButton widget.
Important Signals
The signals are similar to QPushButton widget.
Let us create one simple application to understand this
QRadioButton widget. The details of file names are as shown in
table 1.0.
The Qt Designer file radiobutton_eg1.ui is shown in the
following figure.
import sys
from PyQt5.QtWidgets import QMainWindow,
QApplication
from radiobutton_eg1 import * # RBEG1_1
class MyForm(QMainWindow):
def __init__(self):
super().__init__()
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.ui.rbtn_apple.toggled.connect(lambda:self.myse
lfcheck(self.ui.rbtn_apple)) # RBEG1_2
self.ui.rbtn_orange.toggled.connect(lambda:self.mys
elfcheck(self.ui.rbtn_orange)) # RBEG1_3
self.ui.rbtn_banana.toggled.connect(lambda:self.mys
elfcheck(self.ui.rbtn_banana)) # RBEG1_4
self.show()
def myselfcheck(self, myradiobutton): # RBEG1_5
if myradiobutton.isChecked(): # RBEG1_6
self.ui.lbldisplay.setText(myradiobutton.text() + "
is selected") # RBEG1_7
if __name__=="__main__":
app = QApplication(sys.argv)
w = MyForm()
w.show()
sys.exit(app.exec_())
Case 1
Default output initially on executing the code.
Case 2
When radiobutton with text as Apple is
clicked.
Case 3
When radiobutton with text as Orange is
clicked.
- In RBEG1_1, from radiobutton_eg1.py Python file we are
importing all the members of a module. - In RBEG1_2, we are connecting the toggled signal of
QRadioButton widget rbtn_apple to myselfcheck() method. - In RBEG1_3, we are connecting the toggled signal of
QRadioButton widget rbtn_orange to myselfcheck() method. - From RBEG1_2 to RBEG1_4, using lambda expression, the
signal source is passed as an argument to the method. - In RBEG1_5, myselfcheck() method will take an extra
parameter which acts as sender for QRadioButton widget
for checking its checked state. - In RBEG1_6, will check which QRadioButton widget is
checked. - In RBEG1_7, will display the text of QRadioButton widget
which is checked in the QLabel display widget.
Check Box
Whenever there is a requirement to use a selectable button
and select more than one option, then we shall choose
QCheckBox widget from Widget Box. The appearance of this
widget is a rectangular box before the text label. Unlike
QRadioButton widget, by default, this widget is not mutually
exclusive. However, we can restrict the choice to only one of
the items by adding to the QButtonGroup.
Important Properties
It contains properties of three classes:
- QObject
- QWidget
- QAbstractButton
There is one more property, namely tristate.
Tri-state
This property when set to True, will make the QCheckBox widget
behave as a tri-state checkbox. The default state is False.
Important Methods
- isChecked(): Using this method, Boolean value will be
returned if the QCheckBox widget is selected. - setChecked(): Using this method, we can select/deselect
the QCheckBox widget based on the Boolean value passed. - text(): Using this method, we can retrieve the text of
QCheckBox widget. - setIcon(): Using this method, an icon will be displayed
with QCheckBox widget. - setTriState(): When Boolean value is passed as True, we
are adding third state to QCheckBox widget which is
neither True or False.
Important Signals
The signals are similar to QPushButton widget. In addition to it,
we have stateChanged(int) signal, which will return the QCheckBox
widget’s check state.
Let us create one simple application to understand this
QCheckBox widget. The details of the file names are as shown in
the table below.
The Qt Designer file checkbutton_eg1.ui is shown in the
following figure.
import sys
from PyQt5.QtWidgets import QMainWindow,
QApplication
from checkbutton_eg1 import * # CBEG1_1
class MyCheckButton(QMainWindow):
def __init__(self):
super().__init__()
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.myfruits = {'apple':0, 'orange':0,
'banana':0, 'pear':0} # CBEG1_2
self.ui.chk_Apple.stateChanged.connect(lambda:self.
myselfcheck(self.ui.chk_Apple)) # CBEG1_3
self.ui.chk_Orange.stateChanged.connect(lambda:self
.myselfcheck(self.ui.chk_Orange)) # CBEG1_4
self.ui.chk_Banana.stateChanged.connect(lambda:self
.myselfcheck(self.ui.chk_Banana)) # CBEG1_5
self.ui.chk_Pear.stateChanged.connect(lambda:self.m
yselfcheck(self.ui.chk_Pear)) # CBEG1_6
self.show()
def myselfcheck(self, mychkbutton): # CBEG1_7
if self.ui.chk_Apple.text() == "Apple" : #
CBEG1_8
if self.ui.chk_Apple.isChecked(): #
CBEG1_9
self.myfruits['apple'] = 1
else:
self.myfruits['apple'] = 0
self.mydisplay()
if self.ui.chk_Orange.text() == "Orange" :#
CBEG1_10
if self.ui.chk_Orange.isChecked(): #
CBEG1_11
self.myfruits['orange'] = 1
else:
self.myfruits['orange'] = 0
self.mydisplay()
if self.ui.chk_Banana.text() == "Banana" :#
CBEG1_12
if self.ui.chk_Banana.isChecked(): #
CBEG1_13
self.myfruits['banana'] = 1
else:
self.myfruits['banana'] = 0
self.mydisplay()
if self.ui.chk_Pear.text() == "Pear" :#
CBEG1_14
if self.ui.chk_Pear.isChecked(): #
CBEG1_15
self.myfruits['pear'] = 1
else:
self.myfruits['pear'] = 0
self.mydisplay()
def mydisplay(self):
checkedfruits =', '.join([mykey for mykey
in self.myfruits.keys() if self.myfruits[mykey]==
1]) # CBEG1_16
self.ui.lbl1.setText("You selected: " +
checkedfruits) # CBEG1_17
if __name__=="__main__":
app = QApplication(sys.argv)
w = MyCheckButton()
w.show()
sys.exit(app.exec_())
Case 1
Default output initially on executing the code.
Case 2
When “1” Checkbox button is selected.
Case 3
When “2” Checkbox button is selected.
Case 5
When “4” Checkbox button is selected.
- In CBEG1_1, from checkbutton_eg1.py Python file, we are
importing all the members of a module. - In CBEG1_2, a dictionary object myfruits is created with 4
pairs of key and values. - In CBEG1_3, we are connecting the stateChanged signal of
QCheckBox widget chk_Apple to myselfcheck() method. - In CBEG1_4, we are connecting the stateChanged signal of
QCheckBox widget chk_Orange to myselfcheck() method. - In CBEG1_5, we are connecting the stateChanged signal of
QCheckBox widget chk_Banana to myselfcheck() method. - In CBEG1_6, we are connecting the stateChanged signal of
QCheckBox widget chk_Pear to myselfcheck() method. - From CBEG1_3to CBEG1_6, using lambda expression, the
signal source is passed as an argument to the method. - In CBEG1_7, myselfcheck() method will take an extra
parameter mychkbutton which acts as sender for
QCheckBoxwidget for checking its checked state. - In CBEG1_8 and CBEG1_9, if QCheckBox widget chk_Apple is
checked, then we are changing the value of key ‘apple’
to 1 else it will be 0. - In CBEG1_10 and CBEG1_11, if QCheckBox widget chk_Orange is
checked, then we are changing the value of key ‘orange’
to 1 else it will be 0. - In CBEG1_14 and CBEG1_15, if QCheckBox widget chk_Pear is
checked, then we are changing the value of key ‘pear’ to
1 else it will be 0. - In CBEG1_16, all the items in an iterable here, which we
have used as a list comprehension, will be taken up and
joined as one single string. Here, we are checking the
value for each key item of a dictionary object myfruits as
1. If found True, it will be appended one by one and
will be finally joining as one string. - In CBEG1_17, we are displaying the checked state of each
QCheckBox widget into a QLabel widget lbl1.
Command Link Button
This widget was first introduced in Windows Vista and is a
control widget. The appearance allows for a descriptive text
which is similar to that of QPushButton widget in addition to the
normal text and carries an arrow icon which may indicate
opening of a new GUI form or page or perform any task.
Important Properties
It contains properties of 3 classes.
- QObject
- QWidget
- QAbstractButton
Interestingly, it also contains default and autodefault property
of QPushButton already discussed and description.
Using this property, we are setting a descriptive text on the
button displayed on the smaller font, thus complementing
the label text.
Designer
Important Methods
Generally, there is an empty action list in QCommandLinkButton
widget. However, we can add action/actions or insert action
to the menu of QCommandLinkButton widget. We will learn it
through an example. The most commonly used method is
setDescription().
setDescription
We are setting the descriptive text of QCommandLinkButton widget
using this method and is usually displayed in a smaller font
than the primary text.
Important Signals
The signals are similar to QPushButton widget.
Let us create one simple application to understand this
QCommandLinkButton widget.
The Qt Designer file commandlinkbutton_eg1.ui is shown in the
following figure.
import sys
from PyQt5.QtWidgets import QMainWindow,
QApplication, QAction, QMenu
from commandlinkbutton_eg1 import *
class MyCommandlinkButton(QMainWindow):
def __init__(self):
super().__init__()
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
# Creating 2 QActions object
mya1 = QAction("First Action", self)
mya3 = QAction("Third Action", self)
# Creating QMenu object
mymenu = QMenu()
# adding 2 actions as a list to menu object
mymenu.addActions([mya1, mya3])
# Creating another QAction
mya2 = QAction("Second Action", self)
# inserting myact2 object before mya3
object
mymenu.insertAction(mya3, mya2)
# we are setting menu object to the command
link button
self.ui.clb_btn1.setMenu(mymenu)
# initially counter is set as 0
self.mycount = 0
# connecting clicked signal of command link
button object to slot myincrement(passing
# my count as a parameter) and we are using
lambda expression
self.ui.clb_btn2.clicked.connect(lambda:
self.myincrement(self.mycount))
self.show()
def myincrement(self,mycount): # taking mycount
as another parameter
self.mycount +=1# incrementing the counter
by one.
self.ui.mylbl2.setText("Text Description: :
" + str(self.mycount)) # displaying the counter
value to label object
if __name__=="__main__":
app = QApplication(sys.argv)
w = MyCommandlinkButton()
w.show()
sys.exit(app.exec_())
Case 1
On clicking text with Click Me.
Command_Link_Button/run_commandlinkbutton_eg1.py
Case 2
On clicking text with Increment
commandlinkbutton object once.
Command_Link_Button/run_commandlinkbutton_eg1.py
Dialog Button Box
Whenever there is a requirement to use standard buttons
like OK, Cancel, Ignore, Yes, No and so on. in a layout
automatically on a GUI form, then we can go for
QDialogButtonBox widget. We can also create buttons and add
them to the button box. But this will be a tedious process.
We can see that even in Qt Designer, there are options for
selecting a template as shown in the figure.
right
Important Properties
Apart from the properties of 2 classes (QObject and QWidget),
there are some other properties of QDialogButtonBox widget which will be discussed as follows.
Orientation
Using this property, we can set the orientation of
QDialogButtonBox widget to either Horizontal or Vertical. The
default value is horizontal. If Horizontal is selected, then
buttons will be laid side by side. If Vertical is selected, then
buttons will be laid out stacked on top of each other.
Designer
Standard Button
From a list of standard buttons, we can choose any of them
based on our application. This returns the enum value of
standard buttons corresponding to the given button. By
default, Ok and Cancel standard buttons are checked and will
be displayed in a GUI form, when drag and dropped from
Widget Box.
in Qt Designer
Center Button
When checked, the buttons in the QDialogButtonBox widget will
be centered. It is unchecked by default. This property will
determine whether the buttons in the button box object are
centered horizontally or not. This property can be used to
create dialog boxes that are more visually appealing.
Important Methods
The various important methods are.
- addButton (button): Using this method, standard button
can be added to the QDialogButtonBox widget if valid. Zero
will be returned and will not be added to the
QDialogButtonBox widget if button is invalid. - addButton (button, role): Using this method, the button
can be added to the QDialogButtonBox widget with role
specified. The button will not be added when the role is
invalid. Already added button will already be removed and with
a new role will be added again. - setOrientation (Orientation): Using this method, we can
set the orientation of the QDialogButtonBox widget to
either horizontal or vertical. - setStandardButtons (buttons): Using this method, we can
set the collection of standard Buttons in the
QDialogButtonBox widget.
Important Signals
The important signals of QDialogButtonBox is mentioned in the
figure below.
- accepted(): When the user clicks on a button that accepts the
dialog , then this signal will be emitted. This include buttons
such as Ok, Yes or Save. - rejected(): When the user clicks on a button that rejects the
dialog , then this signal will be emitted. This include buttons
such as Cancel, No or Close. - clicked(QABstractButton*): When the user clicks on any button in
the buttonbox, then this signal will be emitted. It takes a
parameter which is a pointer to the button that was clicked. - helpRequested: When the user clicks on a button that has the
HelpRole role, then this signal will be emitted. This include
buttons such as Help or More Information.
Let us create one simple application to understand this
QCommandLinkButton widget.
The Qt Designer file dialogbuttonbox_eg1.ui is shown in the
figure.
import sys
from PyQt5.QtWidgets import QMainWindow,
QApplication
from dialogbuttonbox_eg1 import *
import webbrowser# importing webbrowser module
class MyDialogButtonBox(QMainWindow):
def __init__(self):
super().__init__()
self.myui = Ui_MainWindow()
self.myui.setupUi(self)
# will act when OK button is clicked and
displayinfo method is executed
self.myui.buttonBox.accepted.connect(self.displayin
fo)
# will act when close button is clicked and
will close the GUI form
self.myui.buttonBox.rejected.connect(self.close)
# will act when help button is clicked
self.myui.buttonBox.helpRequested.connect(lambda:
webbrowser.open("https://auth0.com/blog/username-
password-authentication/"))
self.show()
def displayinfo(self):
if self.myui.lineEdit_2.text() == "1234": #
will check whether password is 1234
# will display the message to the user
self.myui.lbl_display.setText("Username
with " + self.myui.lineEdit.text() + " has login
successfully")
else:
# will display wring password if 1234
is not typed
self.myui.lbl_display.setText("Wrong
Password:")
if __name__=="__main__":
app = QApplication(sys.argv)
w = MyDialogButtonBox()
w.show()
sys.exit(app.exec_())
Output:
Case 1
When wrong password is entered and Ok
button is clicked.
Case 2
When correct password is entered and Ok
button is clicked.
Case 3
When Close button is clicked, GUI form is
closed.
Case 4
When Help button is clicked and if internet is
connected then the above page with link.
https://auth0.com/blog/username-password-authentication/ will be opened.
Common Properties For Button Widget
We will be discussing each property of Button widgets which
are common among each other. Here, we will drag Push Button
widget from the Widget Box into the GUI form and will select
and explain the properties which are common among button widgets. When we will be using the term widget, just imagine
that we are talking about Push Button widget. But the same
may be applied to other widgets too.
Let us go over QObject which are common for all the widgets
of Qt Designer. The QObject is the base class for all Qt classes
and provides a number of features like Property system for
getting and setting the properties of objects, Object trees for
creating hierarchies of objects, Threading as objects can be
safely used from multiple threads, signals, slots, event
handling. which will have already been discussed in our previous section.
objectName
Every widget will have objectName property in Qt Designer as
the above property will hold the widget name. The name
assigned will be used in the Python code as we have seen in
our previous examples.
Property image in Qt Designer can be seen in the figure below.
Enabled
As the name suggests, it decides whether the widget will be
enabled or not. It is checked in Qt Designer by default for
every widget.
Geometry
Relative to its parent, this property holds the widget’s
geometry. In Qt Designer, we have x, y, width and height
where:
- X: x coordinate of the widget relative to its parent on
GUI form. - Y: y coordinate of the widget relative to its parent on
GUI form. - Width: Widget width.
- Height: Widget height.
size policy
This property which got from the class QSizePolicy will tell the
widget’s willingness to be resized, meaning either stretch or
shrink in various ways. Generally, QSizePolicy contains 2
stretch factors and 2 independent size policy which can be
retrieved using horizontalPolicy(), verticalPolicy(),
horizontalStretch() and verticalStretch() functions. We can use
setHeightForWidth() function for indication of widget’s sizeHint()
whether it is width-dependent or not. The horizontalStretch()
and verticalStretch() will return the horizontal and vertical
stretch factor of sizePolicy() respectively.
horizontal or vertical SizePolicy
These components will be present as a comboBox item in Qt
Designer. Property image in Qt Designer can be seen in the
figure.
minimumSize
From the name, we can guess that this property will hold the
minimum size of the widget. The default value will have size
with value as 0 for both width and height. The minimum
permissible height is restricted to this default value.
maximumSize
From the name, we can guess that this property will hold the
maximum size of the widget. The default value will have size
with value as 16777215 for both width and height. The
maximum permissible width is restricted to this default
value.
sizeincrement
This property will hold the widget size increment whose
default values will be 0 for both width and height. baseSize()
will be kept as basis and the size increment will be done
vertically and horizontally in terms of sizeIncrement.height()
pixels and sizeIncrement.width() pixels respectively.
baseSize
This property will hold the widget base size whose default
values will be 0 for both width and height. Here, proper
widget size will be calculated on defining sizeIncrement() by
the widget.size
Palette
There are 3 color groups under this palette property namely
Active, Disabled and Inactive. The Active group will have
keyboard focus for the window, Inactive group is for other
windows and as for Disabled group from the name itself, we
can guess that it is for widgets which are disabled and are often called grayed out. Active and inactive groups mostly
look the same in most styles, while the color groups for each
widget state are contained under QPalette class.
Font
This property will be used to set the font for the widget. We
can set the Family, Point Size and make the text Bold, Italic,
Underline the text, Strikeout the text, spacing between the
letters using kerning and making the text look readable and
smoother on the screen.
Cursor
This property will hold the cursor of the widget, that is,
whatever cursor will be chosen from the pre-defined cursor
list objects, the same will be displayed on widget focus, that is, when it is over the widget. The default cursor object is
Arrow.
Mouse Tracking
From this property, we can enable/disable the mouseTracking for
the widget. It is disabled by default and while the mouse is
moved when at least one mouse button is pressed, the
mouse move events are received by the widget. When
enabled, the mouse move events are received by the widget
irrespective of whether buttons pressed or not.
Tablet tracking
From this property, we can enable/disable the tabletTracking
for the widget. It is disabled by default. When at least one
stylus button is being pressed or there is contact connected
between the stylus and tablet, the tablet move events are
received by the widget. When it is enabled, the tablet move
events are received by the widget even on hovering in close
proximity.
Focus policy
This property defines the keyboard focus acceptance on the
widget. There are different types of focusPolicy.
- NoFocus: The keyboard focus is not at all accepted on
the widget. - TabFocus: The keyboard focus acceptance on the
widget is done by tabbing. - ClickFocus: The keyboard focus acceptance on the
widget is done by clicking. - StrongFocus: The keyboard focus acceptance on the
widget is done by both tabbing and clicking. - WheelFocus: When the wheel of a mouse is moved,
then the widget will accept focus.
Context Menu Policy
This property depicts the display of context menu by the
widget. The default value of this property is DefaultContextMenu.
We can set the other values as NoContextMenu, ActionsContextMenu,
CustomContextMenu and PreventContextMenu.
accept drops
This property allows enabling of drop events for the widget.
Default value is unchecked, that is, set as False and when
checked, that is, value set to True, drop events will be
enabled for the widget.
ToolTip
This property will hold the toolTip of a widget which contains
a default empty string. The behavior of tooltip can be
controlled by intercepting the event() function and catching
the toolTip event. setTooltip() method can be used for
displaying the text in rich text format on a widget.
ToolTip Duration
From the name, we can guess that it will hold the
toolTipDuration of a widget. The default value is -1 and the
duration is mostly calculated based on the toolTip length. The unit will be in milliseconds. So, value of 1000 set in Qt
Designer will be 1 sec.
Status Tip
This property will hold the statusTip of a widget which
contains a default empty string. Property image in Qt
Designer can be seen in the figure.
accessibleName
This property contains a default empty string which will
display the name of the widget when seen by assistive technologies like screenreaders.
accessible Description
This property contains a default empty string which will
display the description of the widget when seen by assistive
technologies.
layout direction
This property will hold the widget’s layout direction, whose
default value will be from LeftToRight. The other values chosen
can be either RightToLeft or LayoutDirectionAuto.
Stylesheet
This property will display the styleSheet of the widget. We can
customize the textual description as per widget’s style. This
property contains a default string. For details, refer Qt style
sheets document.
Locale
This property will display the locale of a widget. We can set
the language and country. Formatting is done using widget’s
locale if there is display of date or number by the widget.
InputMethodHint
This property is pertinent for input widgets which specifically
hints what input method the widget should have. Its default
value is ImhNone. The input method operation depends on
many flags which can be set. If only numbers need to be
entered, then the user can check ImhPreferNumbers. In
addition to it, upper case letters should also be allowed and
then user may check ImhPreferUppercase.
Let us now learn QAbstractButton which are common for all the
Button widgets of Qt designer, except Dialog Button box.
Text
This property will display the text on the Button widgets. An
empty string is returned if the button widget text does not
contain any text. A shortcut is created automatically if an
ampersand character is present in the text, as the shortcut
key will be that character which follows ‘&’. So, there are
chances that the previous shortcut will be cleared or
overwritten. If 2 ‘&&’ are used, then 1 ‘&’ will be displayed.
Icon
This property will display the icon for the button widget
which can be adjusted using iconSize property. There is the
provision of providing scalable icons using QIcon class in
different states and modes.
Icon size
We can set the width and height of the icon size from this
property. The default size is 20*20.
Shortcut
This property will display the mnemonic which is associated
to the button widget.
Checkable
This property will display whether the button widget will be
checkable or not.
Checked
This property will display whether the button widget will be
checked or not. When the button widget is checkable, then
only this widget can be checked. Otherwise by default, it is
unchecked.
auto repeat
This property displays whether autorepeat should be enabled
or not. By default, it is disabled and when it is checked the
signals pressed(), released() and clicked() will be emitted.
autoexclusive
Except for the radio buttons widget, this property is off by
default and when enabled, the buttons which are checkable
behave in the same exclusive button group, such that when
one button is checked, it will uncheck the previous one as at
any time only a single button can be checked. It will have no
effect on buttons that belongs to a button group.
Auto repeat delay
This property will define the auto-repetition initial delay in
milliseconds before activation of auto-repetition when
autoRepeat is enabled. The default value set is 300 msecs.
Auto repeat interval
This property will define the auto-repetition interval length in
milliseconds when autoRepeat is enabled. It is set as 100msec
by default.
Conclusion
In this section, we have learned in-depth understanding of
Button widgets in Qt Designer. Button widgets are widely
used for creating interactive user interfaces and their
properties, functionality and customization options have
been thoroughly explained. By exploring the features and
settings related to Button widgets, the user can effectively
design and implement user-friendly interfaces in their Qt
Applications. Qt Designer offers a variety of Button widgets, including CheckBox, Push Button, Tool Button, Radio Button and
Command Link Button each serving a specific purpose. Moreover,
we have seen different Dialog Button Box present in Qt
Designer. The section explores the description, properties,
important methods and signals associated with each button
widget. Additionally, an application example with an output
display is provided to illustrate the practical implementation
of Button widgets. Furthermore, the section covers the
important properties of QObject, QWidget and QAbstractButton,
which are relevant to Button widgets. These properties are
supplemented with images to enhance understanding.
In the next section, we will learn about Item Views in Qt
designer which are commonly used for creating interactive
user interfaces. We will learn how data will be presented in
the form of list, hierarchical tree structures and tabular
representations.