Python Graphical User Interface
When it comes to building intuitive and well structured GUI applications, mastering key components such as the Group Box, Scroll Area, Tool Box and others is essential. Each element serves a distinct purpose in organizing and enhancing user experience. Whether you are stacking content with the Tab Widget or Stacked Widget or creating interactive, multi-window interfaces with the MDI Area and Dock Widget understanding how these components function can transform your application from basic to professional. This article will walk you through these core elements, explaining how they work together to build dynamic and user-friendly applications. Let’s dive into each widget and explore their powerful capabilities.
Table of Content
Introduction
- Group box
- Scroll area
- Tool box
- Tab widget
- Stacked widget
- Frame
- Widget
- MDI area
- Dock widget
Introduction
In order to organize and properly position child widgets
within a parent widget, PyQt5 container widgets are used.
These container widgets determine the position and size of
child widgets within the parent widget and allow for the
creation of a layout. If there were no container widgets, child
widgets might not be properly arranged, overlap or be
hidden on the screen. Container widgets allow easy layout
manipulation, such as the alignment of widgets to the left or
right or the change of space between the widgets. We have
already learned about layout management previously. In this
chapter, we shall concentrate on different PyQt5 container
widgets of Qt Designer as shown in the figure 1.1.
Group Box
A QGroupBox is a widget from the Qt GUI library that acts as a
container to group other widgets together and is visually
distinguished from other widgets by a title and a frame. It
can be used to organize related widgets into a single unit,
simplifying the interface’s comprehension and navigation.
The QGroupBox can be exclusive, which means that only one
Group Box in a parent container can be checked at a time as
well as checkable, which indicates that it can be checked or
unchecked by the user. Any widget from the PyQt5 can be
added into the QGroupBox object.
Important Properties
Let us go over some important properties now.
Title
We can set the text that appears in the QGroupBox object title
bar.
Alignment
We can set the alignment of the title within the QGroupBox
object’s frame either vertically or horizontally. Users can
choose multiple options from either of these alignments.
Flat
We can set the appearance to be either a frame or painted
flat of QGroupBox object. By default, it is disabled.
Checkable
We can make the QGroupBox object title checkable with the
help of this property. The title is displayed with the help of a
checkbox instead of an ordinary label if set to True. The
QGroupBox object’s children are enabled if checked else
disabled. By default, it is set to False.
Checked
This property will be used only if the checkable property is
set to True for the QGroupBox object. By default, it is
unchecked and disabled. But if the QGroupBox object checkable
property is set to True, this will also be set to True.
Important Methods
- setTitle(title): We can set the text that appears in the
QGroupBox object title bar with the help of this method. It
will have a keyboard shortcut if the title text contains
an & followed by a letter. - setCheckable(checkable): If set to True, QGroupBox object is
checkable. - isCheckable(): Will return True if QGroupBox object is
checkable else False. - setAlignment(alignment): We can set the alignment of
QGroupBox object. - setFlat(flat): Using this method, we can set the
appearance to be either frame or painted flat of
QGroupBox object. - isChecked(): Will return True if QGroupBox object is
checked else, False.
Now, we shall see an example of QGroupBox widget.
Consider the following code of run_groupboxWidget_eg1.py:
import sys
from PyQt5.QtWidgets import QMainWindow,
QApplication
from groupboxWidget_eg1 import *
class MyGroupBoxWidget(QMainWindow):
def __init__(self):
super().__init__()
self.myui = Ui_MainWindow()
self.myui.setupUi(self)
self.myui.groupBox.setCheckable(True)
self.myui.groupBox.setChecked(False)
# Connect the group box's toggled signal to
the handle_toggled slot
self.myui.groupBox.toggled.connect(self.mytoggle)
self.show()
def mytoggle(self,mychecked):
print(mychecked)
# Updating the label based on GroupBox
checked status
if mychecked:
self.myui.lbl1.setText("Label1 On")
self.myui.lbl1.setStyleSheet("QLabel {
color : green; }")
self.myui.lbl2.setText("Label2 Off")
self.myui.lbl2.setStyleSheet("QLabel {
color : red; }")
else:
self.myui.lbl2.setText("Label2 On")
self.myui.lbl2.setStyleSheet("QLabel {
color : green; }")
self.myui.lbl1.setText("Label1 Off")
self.myui.lbl1.setStyleSheet("QLabel {
color : red; }")
if __name__=="__main__":
app = QApplication(sys.argv)
w = MyGroupBoxWidget()
w.show()
sys.exit(app.exec_())
Output
We are providing the QGroupBox object checkable status with
initial state as unchecked.
Case 1 — When the QGroupBox object is checked
When the QGroupBox object is checked, then Label1 text is set to
Label1 On, and the color is changed to Green Here, legend is
added as Green in bracket for better understanding of all the
readers. On the other hand, the Label2 text is set to Label2
Off, and the color is set to Red. Here, legend is added as Red
in bracket for betterunderstanding of all the readers.
Case 2 — When the QGroupBox object is unchecked
When the QGroupBox object is unchecked, then the Label2 text is
set to Label2 On, and the color is changed to Green Here,
legend is added as Green in bracket for better understanding
of all the readers. On the other hand, Label1 text is set to
Label1 Off, and the color is set to Red Here, legend is added as
Red in bracket for better understanding of all the readers.
Scroll Area
A QScrollArea widget in PyQt5 is a container widget that
provides scrolling capabilities for the child widget contents
within a frame. It can be used to display large or complex
content, such as a picture, a table, or a written document,
that is too big to fit in a single viewport. When a child widget
is larger than the viewport, the QScrollArea widget
automatically adds scroll bars.
Important Properties
This QScrollArea widget also contains properties from classes
we have already discussed QFrame and QAbstractScrollArea.
Widget Resizable
When set to True, the QScrollArea object will automatically
resize the widget to fit the viewport. The default value is set
to True.
Designer
Alignment
We can set the alignment of the title within the QScrollArea
object’s frame either vertically or horizontally. Users can
choose multiple options from either of these alignments.
Important Methods
- setWidget(widget): We can set the widget contained
within the scroll area. The widget will be destroyed
when the scroll area is deleted, as it becomes a child of
the scroll area. - setWidgetResizable(resizable): Using this method, we can
set the widget contained within the scroll area to be
resized to fit the area. - ensureVisible(x,y[, xmargin=50[, ymargin=50]]): This method
ensures that the point (x, y) is visible within the scroll
area with an optional margin. The margins are
specified in pixels, with the default value for both
margins to be 50 pixels. - setAlignment(arg__1): We can set the alignment of the
QScrollArea object. The default value will be aligned to
the top-left of the scroll area.
Important Signals
Some important signals are as follows.
ScrollContentBy(int dx, int dy)
We can use the QScrollArea object in the following way:
- First, create an instance of QScrollArea object.
- Next, create a child widget for display within the scroll
area. - Set the widget property of the QScrollArea object to the
child widget. - Finally, add the QScrollArea object to the layout.
Now, we shall see an example of the QScrollArea widget.
Consider the following code of run_scrollAreaWidget_eg1.py:
import sys
from PyQt5.QtWidgets import QApplication,
QMainWindow,QLabel, QPushButton,
QVBoxLayout,QHBoxLayout,QGroupBox,QWidget
from scrollAreaWidget_eg1 import *
class MyScrollAreaWidget(QMainWindow):
def __init__(self):
super().__init__()
self.myui = Ui_MainWindow()
self.myui.setupUi(self)
self.myui.top_widget = QWidget()
self.myui.top_layout = QVBoxLayout()
# Step-1: Already a QScrollArea object was
created in Qt Designer
# Step-2 : Creation of 8 different child
widgets (groupbox having label and pushbutton)
within the scroll area
for loop in range(8):
# creating groupbox widget instance
self.myui.group_box = QGroupBox()
# setting the groupbox title
self.myui.group_box.setTitle('GroupBox
Item No. {0}'.format(loop))
# creating a hboxlayout instance to the
groupox widget
self.myui.layout =
QHBoxLayout(self.myui.group_box)
# creating a label object, setting the text and adding it to the hboxlayout instance
self.myui.label = QLabel()
self.myui.label.setText('Label For Item
No. {0}'.format(loop))
self.myui.layout.addWidget(self.myui.label)
# creating a [pushbutton] object,
setting the text and size and adding it to the
hboxlayout instance
self.myui.push_button = QPushButton()
self.myui.push_button.setText('Display
Button')
self.myui.push_button.setFixedSize(100,
32)
self.myui.layout.addWidget(self.myui.push_button)
# adding the groupbox object to the
vboxlayout
self.myui.top_layout.addWidget(self.myui.group_box)
# adding the vbox layout to the child
widget
self.myui.top_widget.setLayout(self.myui.top_layout)
# Step-3: Setting the widget property of
the QScrollArea object to the child widget
self.myui.scrollArea.setWidget(self.myui.top_widget)
# Step-4: Already the QScrollarea object is
added to the vboxlayout in Qt Designer
self.show()
if __name__=="__main__":
app = QApplication(sys.argv)
w = MyScrollAreaWidget()
w.show()
sys.exit(app.exec_())
Output
Tool Box
The toolbox widget is one of the widgets available in the Qt
Designer to create a user interface. By dragging the toolbox
item from the Containers area of the widget box onto the
form in Qt Designer, the toolbox widget may be added to a
form. A toolbox is a widget that shows a column of tabs
stacked one on top of the other, with the current item
showing up below the active tab. Each tab has a certain
index location within the tab column. A QWidget is an item in a
tab. The column of tabbed widget items is provided by the
QToolBox class.
Important Properties
Let us check some important properties.
Current Index
This property holds the index of the currentItem of the QToolBox
object. -1 value is returned for an empty QToolBox object.
Designer
Current Item Text
This property holds the currentItemText of the QToolBox object.
Designer
Current Item Name
This property holds the currentItemName of the QToolBox object.
Designer
Current Item Icon
This property holds the currentItemIcon of the QToolBox object.
Designer
Current Item Tooltip
This property holds the currentItemToolTip of the QToolBox
object.
Designer
Tab Spacing
This property will set the spacing between the tab bar and
the pages of the QToolBox object. It is measured in pixels.
Important Methods
- addItem(widget, text): This method will add a given
widget in a new tab at the bottom of the QToolBox object where the text of the new tab is set to text. - count(): This method will return the number of items
contained in the QToolBox object. - currentIndex(): This method will return the currentItem
index of the QToolBox object. - insertItem (index, widget, text): This method will insert a
widget at the index specified or the QToolBox object’s
bottom if the index is out of range. The text of the new
item is set to text. It returns the index of the new item. - itemToolTip(index): This method returns the tooltip for
the item at the specified index, or an empty string is
returned if the index is out of range. - indexOf(widget): This method will return the index of the
given widget, or -1 if the widget is not a child of the
QToolBox object. - itemText(index): This method will return an empty string
if the index is outside of the range or the text of the
item at the position index of the QToolBox object.
Important Signals
Let us check some important signals.
Current Changed Index
This signal is emitted when the current item of the QToolBox
object is changed.
Now, we shall see an example of QToolBoxwidget.
Consider the following code of run_toolBoxWidget_eg1.py:
import sys
from PyQt5.QtWidgets import
QMainWindow,QApplication,QLabel, QToolBox
from toolBoxWidget_eg1 import *
class MyToolBox(QMainWindow):
def __init__(self):
super().__init__()
self.myui = Ui_MainWindow()
self.myui.setupUi(self)
# creating an instance of QToolBox item
self.myui.toolBox = QToolBox()
# aading the widget QToolBox to the
GridLayout
self.myui.gridLayout.addWidget(self.myui.toolBox
,0,0)
# Adding 3 Label items to the ToolBox
widget
mylbl1 = QLabel()
self.myui.toolBox.addItem(mylbl1, "Item1")
mylbl2 = QLabel()
self.myui.toolBox.addItem(mylbl2, "Item3")
mylbl3 = QLabel()
self.myui.toolBox.addItem(mylbl3, "Item4")
# disabling first tab --> 0
self.myui.toolBox.setItemEnabled(0, False)
# returns true if tems at specifiied
positions are enabled
print(self.myui.toolBox.isItemEnabled(0))
print(self.myui.toolBox.isItemEnabled(1))
# inserting Label at index specified
position:1
myitem = QLabel()
self.myui.toolBox.insertItem(1, myitem,
"Item2")
# displaying number of items
print(self.myui.toolBox.count())
# mouseover tooltip at different tabs
self.myui.toolBox.setItemToolTip(0, "This
is Item1") # displaying at tab1
self.myui.toolBox.setItemToolTip(1, "This
is Item2") # displaying at tab2
self.myui.toolBox.setItemToolTip(2, "This
is Item3") # displaying at tab3
self.myui.toolBox.setItemToolTip(3, "This
is Item4") # displaying at tab4
self.show()
if __name__ == "__main__":
app = QApplication(sys.argv)
screen = MyToolBox()
screen.show()
sys.exit(app.exec_())
Output
Tab Widget
A stack of tabbed widgets is provided by the QTabWidget class.
The PyQt5 library’s QTabWidget class offers a tabbed widget for
managing multiple widgets in a single window. A tab widget
offers a tab bar and a page area where pages associated
with each tab can be shown. The tab bar is displayed above
the page area by default, although different configurations
are available. By clicking on the tabs at the widget’s top, the user can navigate between various pages of widgets. The
tabs can be moved around and removed as needed and
each tab has a separate widget inside. Additionally, the
QTabWidget class has signals and slots for controlling the
current tab.
Important Properties
Some important properties are as follows.
Tab Position
We can determine the tab’s position in the QTabWidget object
using this property. Possible values can be chosen from the
drop-down menu, as the default value is North.
Designer
Tab Shape
We can determine the tab’s shape using the above property
from QTabWidget object. Default value is rounded as possible
values can be chosen from the drop-down menu.
Current Index
We can determine the index position of the current tab page
of QTabWidget object. Default value is -1 if there are no tabs in
the QTabWidget object.
Designer
Icon Size
We can determine the icon size on the tab bar, which is a
QSize object.
Elide Mode
When there is insufficient space to display items for a
specific tab bar size, this property determines how items
should be elided. Possible values can be chosen from the
drop-down menu.
Designer
User Scroll Buttons
When the tab bar is too small to display all the tabs, this
parameter specifies whether the tab bar should use scroll
buttons or not.
Designer
Document Mode
This property, when set to True, that is, in document mode,
tabs should be displayed as documents rather than tool
buttons.
Designer
Tabs Closable
When set to True, the close buttons will be automatically
added to each tab of QTabWidget object.
Designer
Movable
When set to True, the user can move tabs within QTabWidget
object.
Tab Bar Auto Hide
When set to True, the tab bar is automatically hidden when
it contains less than 2 tabs.
Designer
Current Tab Text
This property determines the text of the current tab of
QTabWidget object.
Designer
Current Tab Name
This property determines the name of the current tab of
QTabWidget object.
Designer
Current Tab Icon
This property determines the icon of the current tab of
QTabWidget object.
Designer
Current Tab Tooltip
This property determines the tooltip of the current tab of
QTabWidget object.
Designer
Current Tab What’s This
This property determines the What is This? Help of the
current tab of QTabWidget object.
Qt Designer
Important Methods
- addTab(widget, arg__2): A new tab will be added to the
QTabWidget object with the given page and label as the
text of the tab and the index of the tab in the QTabWidget
object is returned. - currentIndex(): The index position of the current tab
page will be returned. - removeTab(index): This method will remove the tab at the
specified index from the QTabWidget object. - count(): This method will return the number of tabs in
the QTabWidget object. - tabText(index): This method will return the tab text of the
QTabWidget object at the specified index. - setTabText(index,text): This method will set the tab text
by defining a new label at the specified position index’s
tab of the QTabWidget object. - insertTab(index,widget,arg__3): A new tab is inserted at a
specified index with a given widget and a label. The
new tab should be inserted at the position specified by
the index parameter. A new tab is inserted at the
beginning if the index is less than or equal to 0. The
new tab is appended at the end if the index is more
than or equal to the number of tabs that are already
present.
Important Signals
Some important signals are as follows.
Current Changed
When the current tab is changed, this signal is emitted. The
new current tab’s index is the index parameter passed to the
signal handler. When the user switches between tabs, this
signal can be used to update the application’s state or
perform other actions.
Tab Close Requested
When the user requests to close a tab, this signal is emitted.
The signal handler’s index parameter contains the index of
the tab that the user wants to close. The user may be
prompted to save any changes that have not yet been saved
or to perform other actions before closing the tab using this
signal.
Now, we shall see an example of QTabwidget.
Consider the following code of run_tabWidget_eg1.py:
import sys
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QApplication,
QMainWindow, QPushButton,QFormLayout,
QLineEdit,QHBoxLayout,QRadioButton,QMessageBox,
QTabWidget, QWidget
from tabWidget_eg1 import *
class MyTabWidget(QMainWindow):
def __init__(self):
super().__init__()
self.myui = Ui_MainWindow()
self.myui.setupUi(self)
self.myui.tabWidget.clear()
self.myui.tabWidget.setTabsClosable(True) #
Allow tabs to be closed by the user
self.myui.tabWidget.tabCloseRequested.connect(self.
handleCloseTab) # Connect the tabCloseRequested
signal to the handleCloseTab slot
# adding 3 LineEdit widget to tab1 and
adding it to tabwidget
mylayout = QFormLayout()
mylayout.addRow("Name: ",QLineEdit())
mylayout.addRow("PhoneNo: ",QLineEdit())
mylayout.addRow("Age: ",QLineEdit())
self.tab1 = QWidget()
self.tab1.setLayout(mylayout)
# Creating Tab1 and adding widgets
self.myui.tabWidget.addTab(self.tab1, "Tab1")
# Adding only 1 QLineEdit to tab2 of tabwidget
self.myui.tabWidget.addTab(QLineEdit(),"Tab 2")
# Adding 2 Radio Buttons to tab3 of tabwidget
mylayout2 = QFormLayout()
mysex = QHBoxLayout()
mysex.addWidget(QRadioButton("Male"))
mysex.addWidget(QRadioButton("Female"))
mylayout2.addRow("Sex",mysex)
self.tab3 = QWidget()
self.tab3.setLayout(mylayout2)
# Creating Tab3 and adding widgets
self.myui.tabWidget.addTab(self.tab3, "Tab3")
# Change the tab position to the bottom
self.myui.tabWidget.setTabPosition(QTabWidget.South)
# Disabling the second tab
self.myui.tabWidget.setTabEnabled(1, False)
# Setting the current tab as Tab 3
self.myui.tabWidget.setCurrentIndex(2)
self.show()
def handleCloseTab(self, index):
"""
Handling the tabCloseRequested signal by
prompting the user to save any unsaved changes
"""
mytab_widget =
self.myui.tabWidget.widget(index)
if isinstance(mytab_widget, QLineEdit): #
if closing QLineEdit tab
myresult = QMessageBox.question(self,
"Unsaved Changes", "Do you want to save your
changes and remove?", QMessageBox.Save |
QMessageBox.Cancel)
if myresult == QMessageBox.Save:
# Save the changes
print("Save")
self.myui.tabWidget.removeTab(index)
pass
else:
# Cancel the tab close request
print("Cancelled")
return
else:
# No unsaved changes, just remove the
tab
self.myui.tabWidget.removeTab(index)
if __name__ == '__main__':
app = QApplication(sys.argv)
w = MyTabWidget()
w.show()
sys.exit(app.exec_())
Output
Stacked Widget
In PyQt5, a stacked widget is a means to organize several
widgets into a single container, each only displays one
widget at a time. It is comparable to a QTabWidget but offers
more layout and appearance flexibility. The QtWidgets
module’s stacked widget can be used to arrange multiple
widgets in a stacked layout. QStackedWidget can be constructed
and populated with various child widgets pages.
Important Properties
QStackedWidget contains QFrame class properties which we have
already discussed on Item Views section 5, Getting Insights
of Item Views in Qt Designer. Apart from that it has
currentIndex property.
Current Index
We can determine the widget’s index position which is
visible. Value is -1 if there is no current widget.
Designer
Important Methods
- addWidget(QWidget): This method will take a QWidget object
as an argument and append it to the QStackedWidget
object, which will return the index position. - count(): The number of widgets contained by the QStackedWidget object is returned.
- currentWidget(): This method will return the current
widget, which is displayed in the QStackedWidget object,
and will return None if there are no child widgets.
Important Signals
Some important signals are as follows.
Current Changed(arg__1)
This signal is emitted when the current widget in the stack changes of QStackedWidget object.
Widget Removed
This signal is emitted when the widget is removed from the
stack of QStackedWidget object.
Now, we shall see an example of QStackedWidget. Here, we are
directly writing Python code and importing QWidget class.
Consider the following code of run_StackedWidget_eg1.py:
import sys
from PyQt5.QtWidgets import *
class MyStackedWidget(QWidget):
def __init__(self):
super().__init__()
self.listWidget = QListWidget()
self.listWidget.insertItem(0,"Details")
self.listWidget.insertItem(1,"Hobby")
self.listWidget.insertItem(2,"Sex")
# creating an instance of QWidget
self.mystack1 = QWidget()
self.mystack2 = QWidget()
self.mystack3 = QWidget()
self.mystack1UI()
self.mystack2UI()
self.mystack3UI()
self.listWidget.currentRowChanged.connect(self.my_o
n_current_changed)
self.mystackwidget = QStackedWidget(self)
# Setting the current widget to the first
one in the stack
self.mystackwidget.setCurrentIndex(0)
# adding the widgets to the QStackedWidget
object
self.mystackwidget.addWidget(self.mystack1)
self.mystackwidget.addWidget(self.mystack2)
self.mystackwidget.addWidget(self.mystack3)
hbox = QHBoxLayout(self)
hbox.addWidget(self.listWidget)
hbox.addWidget(self.mystackwidget)
self.setLayout(hbox)
self.show()
# Connect the currentChanged signal to a slot
def my_on_current_changed(self,index):
print("The current widget is changed to
index no:", index)
self.mystackwidget.setCurrentIndex(index)
def mystack1UI(self):
#adding the widgets to the first stack
mylayout1 = QFormLayout()
mylayout1.addRow("Name",QLineEdit())
mylayout1.addRow("Age",QLineEdit())
mylayout1.addRow("City",QLineEdit())
self.mystack1.setLayout(mylayout1)
def mystack2UI(self):
#adding the widgets to the second stack
mylayout2 = QFormLayout()
mylayout2.addRow(QCheckBox("Playing
Chess"))
mylayout2.addRow(QCheckBox("Cooking"))
mylayout2.addRow(QCheckBox("Reading Books"))
self.mystack2.setLayout(mylayout2)
def mystack3UI(self):
#adding the widgets to the third stack
mylayout3 = QHBoxLayout()
mylayout3.addWidget(QLabel("Sex: "))
mylayout3.addWidget(QRadioButton("Male"))
mylayout3.addWidget(QRadioButton("Female"))
self.mystack3.setLayout(mylayout3)
if __name__ == '__main__':
app = QApplication(sys.argv)
w = MyStackedWidget()
w.show()
sys.exit(app.exec_())
Output
Frame
The PyQt5 widget QFrame acts as a simple container for other widgets. It has characteristics like the frame form, shadow and line width that can be used to make simple shapes or
borders as well as to group other widgets together. A wide
range of custom user interface components, including
dialogs, Group Boxes and custom forms, can be made with
it. We can create simple placeholder frames with no contents
using the QFrame class.
Important Properties
We have already discussed about properties of QFrame when
we were dealing with Item View widgets section 5, Getting
Insights of Item Views in Qt Designer.
Important Methods
- setFrameShape(arg__1): This method can be used for setting
the frame shape value of QFrame object. - setFrameShadow(arg__1): This method can be used for
setting the frame shadow value of QFrame object. - setLineWidth(arg__1): This method can be used for setting
the line width value of the QFrame’s border. - setMidLineWidth(arg__1): This method can be used for
setting the mid-line width value of the QFrame’s border.
Now, we shall see an example of QFrame.
Consider the following code of run_frame_eg1.py:
import sys
from PyQt5.QtWidgets import QApplication,
QMainWindow, QFrame, QLabel, QLineEdit,
QPushButton,QVBoxLayout
from frame_eg1 import *
class MyFrame(QMainWindow):
def __init__(self):
super().__init__()
self.myui = Ui_MainWindow()
self.myui.setupUi(self)
# Setting the frame shape to a box
self.myui.frame.setFrameShape(QFrame.Box)
# Setting the frame shadow to raised
self.myui.frame.setFrameShadow(QFrame.Raised)
# Setting the line width of the border to 2
self.myui.frame.setLineWidth(2)
# Creating a QVBoxLayout to hold our
widgets
layout = QVBoxLayout()
# Adding a label and a line edit to the
layout
layout.addWidget(QLabel("My Name:"))
layout.addWidget(QLineEdit())
layout.addWidget(QPushButton("Frame Btn"))
# Adding the layout to the frame
self.myui.frame.setLayout(layout)
self.show()
if __name__=="__main__":
app = QApplication(sys.argv)
w = MyFrame()
w.show()
sys.exit(app.exec_())
Output
Widget
The Python bindings for the Qt libraries include the class
QWidget in PyQt5 library. In the PyQt5 library, it serves as the
base class for all user interface objects. QWidgets can be used
as containers for other widgets as well as to generate user
interface components like buttons, labels, and text fields. A
widget is clipped by the widgets in front of it as well as by its
parent widget. A window is a widget that is not contained
within a parent widget. Although it is also possible to create windows without decoration by using the appropriate window
flags, windows typically feature a frame and a title bar.
Important Properties
We have already seen the properties of QWidget in section 4,
Getting Insights of Button Widgets in Qt Designer. The
default values may be changed, but the number of
properties remains the same.
Important Methods
- setGeometry(x,y,width,height): This method will set the
widget geometry, including its size and position. - setWindowTitle(arg__1): We can set the window title
containing the widget with this method. - show(): This method will display the widget and its child
widgets. - resize(width,height): The widget will be resized to the
specified width and height using this method. - move(x,y): This method will help the widget to move to
the specified x and y coordinates. - setLayout(arg__1): This method will set the layout of a
widget where the first argument is the first argument
is layout object which we want to set, and the second
argument is the widget on which we want to set the
layout on. - setStyleSheet(stylesheet): We can set the widget’s
stylesheet to the stylesheet, The Qt Style Sheets
document’s textual description of the widget’s style
modifications customizations is contained in the style
sheet.
Important Signals
- customContextMenuRequested(pos): When the widget’s context
menu is requested, this signal is emitted. The mouse
pointer’s global position is supplied to it as a QPoint.
When the context menu is requested, it can be
connected to a slot function to carry out a specific
action. - windowIconChanged(icon): When the window icon is
changed, this signal is emitted, which passes the new
icon. - windowIconTextChanged(iconText): When the window icon
text is changed, this signal is emitted, which passes the
new icon text. - windowTitleChanged(title): When the window title is
changed, this signal is emitted, which passes the new
window title.
Now, we shall see an example of QWidget.
Consider the following code of run_widget_eg1.py:
import sys
from PyQt5.QtWidgets import QApplication,
QMainWindow, QWidget
app = QApplication(sys.argv)
# Creating an instance of QWidget and will be the
main window of the application
mywidget = QWidget()
# Setting the size and position of the screen
widget
mywidget.resize(350, 150)
mywidget.move(250, 250)
# Setting the widget title
mywidget.setWindowTitle("Basic QWidget Eg")
# Display the widget on the screen
mywidget.show()
sys.exit(app.exec_())
Output
MDI Area
The QMdiArea widget provides an area where Multiple
Document Interface windows can be displayed. In
order to build each window separately for displaying many
windows at once, Single Document Interface can be
used. Since each window may have its own menu system,
toolbar and so on, this requires extra memory resources.
Applications that use the MDI interface use less memory. The
sub windows are arranged in relation to one another inside
the main container, naming the container widget as QMdiArea.
Typically, the QMainWindow object’s center widget is the QMdiArea
widget. The QMdiSubWindow class is represented by the child
windows in this section. Any QWidget may be chosen to serve
as the internal widget for the subWindow object. In the MDI
area, sub-windows may be set up in a tiled or cascading
pattern.
Important Properties
Let us now go over some important properties as follows.
Background
The background brush for the workspace area can be set by
using this property. By default, it is a grey color.
Designer
Activation Order
The ordering criteria in which the sub-windows are activated
are specified using this property.
Qt Designer
View Mode
This property specifies the mode in which the sub-windows
are displayed within the QMdiArea object.
Designer
Document Mode
This property specifies whether the Document/View
architecture should be used by the QMdiArea object or not. The
QMdiArea object will manage its sub windows using this
architecture if it is enabled. By default, it is unchecked.
Qt Designer
Tabs Closable
This property specifies whether the tabs of sub-windows in
the QMdiArea object should have a close button or not. By
default, it is set to False.
Designer
Tabs Movable
This property specifies whether the tabs of sub-windows in
the QMdiArea object should be movable or not. By default, it is
set to False.
Designer
Tab Shape
This property specifies the tab shape in the QMdiArea object.
Designer
Tab Position
This property specifies the tab position in the QMdiArea object.
Designer
- addSubWindow(widget[, flags=Qt.WindowFlags()]): This method
will add the widget as a new sub-window to the MdiArea
which will override the flags set on the widget when
WindowFlags are non-zero. - removeSubWindow(widget): This method will reduce the
widget which can be either an internal widget of a
sub-window or a QMdiSubWindow from the MdiArea. - activeSubWindow(): A pointer is returned to the current
active sub-window else, None is returned if no window
is currently active. - cascadeSubWindows(): This method will arrange all sub
windows in a cascading pattern. - tileSubWindows(): This method will arrange all sub
windows in a tiled pattern. closeActiveSubWindow(): The currently active sub window is
closed using this method. - SubWindowList([order = CreationOrder]): A list of sub-
windows is returned in the QMdiArea object. The default
order is the CreationOrder, which means sorting will be
done in the order in which they were inserted into the
workspace. - setWidget(): Using this method, a QWidget is set as an
internal widget of a QMdiSubWindow instance.
Important Signals
Let us go over some important signals now.
Sub Window Activated(arg__1)
When a sub-window within the MDI area becomes the active
window, the subWindowActivated signal in QMdiArea object is
emitted. arg__1 refers to the newly active sub-window.
Now, we shall see an example of QMdiArea.
Consider the following code of run_mdiarea_eg1.py:
import sys
from PyQt5.QtWidgets import QApplication,
QMainWindow, QMdiArea, QMdiSubWindow, QTextEdit,
QMenu, QMenuBar, QAction
from mdiarea_eg1 import *
class MyMdiArea(QMainWindow):
def __init__(self):
super().__init__()
self.myui = Ui_MainWindow()
self.myui.setupUi(self)
# Setting QMdiArea object as the central
widget
self.setCentralWidget(self.myui.mdiArea)
# Adding three QTextEdit sub-windows to the
QMdiArea object
mysub1 = QMdiSubWindow()
mysub1.setWidget(QTextEdit())
mysub1.setWindowTitle("Window 1")
self.myui.mdiArea.addSubWindow(mysub1)
mysub2 = QMdiSubWindow()
mysub2.setWidget(QTextEdit())
mysub2.setWindowTitle("Window 2")
self.myui.mdiArea.addSubWindow(mysub2)
mysub3 = QMdiSubWindow()
mysub3.setWidget(QTextEdit())
mysub3.setWindowTitle("Window 3")
self.myui.mdiArea.addSubWindow(mysub3)
# Creating a menu bar and adding two
actions to it
mymenubar = self.menuBar()
mywindowMenu = mymenubar.addMenu("Display As")
mycascadeAction = QAction("Cascade", self)
mycascadeAction.triggered.connect(self.myui.mdiArea
.cascadeSubWindows)
mywindowMenu.addAction(mycascadeAction)
mytileAction = QAction("Tile", self)
mytileAction.triggered.connect(self.myui.mdiArea.ti
leSubWindows)
mywindowMenu.addAction(mytileAction)
self.show()
if __name__ == "__main__":
app = QApplication(sys.argv)
screen = MyMdiArea()
screen.show()
sys.exit(app.exec_())
Output
Dock Widget
QDockWidget class allows users to add dockable windows to a
main window. It offers a container widget that may be
floated as a separate window or docked to the sides of a
main window. The QDockWidget is capable of supporting
features, including floating windows, movable and closable
tabs. It is frequently used to provide users the ability to
arrange the application’s interface layout to meet their
demands.
The idea of dock widgets, commonly referred to as tool
palettes or utility windows, is presented by QDockWidget. Dock
windows are secondary windows that are placed in a QMainWindow’s dock widget area around the central widget. A
title bar and content area make up a QDockWidget. The window title, a float button, and a close button are all displayed in
the title bar of the dock widgets. The float and close buttons
may be either hidden or not displayed at all depending on
the state of the QDockWidget.
Important Properties
Let us check some important properties now.
Floating
If this Boolean property is set as True, then the dock widget
is set as floating.
Features
This property will determine the features enabled for the
dock widget, that is, can be set as movable, closable or
floatable.
Allowed Areas
This property will determine the dockwidget areas in which the
dock widget can be placed.
Designer
Window Title
The dock widget title is set using this property.
Designer
Dock Widget Area
The current dock widget area of the dock widget is returned
by using this property.
Designer
Docked
By using this property, we can determine whether the dock
widget is docked or floating.
Important Methods
- isAreaAllowed(area): A boolean value True is returned if
the dock widget can be placed in the specified dock
widget area else, False is returned. - widget(): A widget is returned contained in the dock
widget. If the widget has not been set, zero will be
returned. - toggleViewAction(): This method will return a checkable
action that can be added to toolbars and menus so that
the user can toggle the visibility of the dock widget.
Important Signals
- allowedAreasChanged(allowedAreas): The allowedAreasChanged
signal is emitted when the allowed areas for a dock
widget change. The argument allowedAreas specifies the
new allowed areas. - dockLocationChanged(area): Signal is emitted when
QDockWidget object is moved to a new location specified
by the area argument. - featuresChanged(features): Signal is emitted when there is
change in the QDockWidget object features. - topLevelChanged(topLevel): Signal is emitted when the dock
widget changes its top-level state, that is, whether it is
floated as a top-level window or docked inside a main
window where the topLevel argument specifies the new
state. - visibilityChanged(visible): Signal is emitted when
QDockWidget object visibility changes.
Now, we shall see an example of QDockWidget.
Consider the following code of run_dockWidget_eg1.py:
import sys
from PyQt5 import QtWidgets, QtCore
myapp = QtWidgets.QApplication(sys.argv)
# Creating a main window object
mymainWindow = QtWidgets.QMainWindow()
# Creating a dock widget object
dockWidget = QtWidgets.QDockWidget("Dock Widget",
mymainWindow)
# Setting the allowed dock widget areas
dockWidget.setAllowedAreas(QtCore.Qt.LeftDockWidget
Area | QtCore.Qt.RightDockWidgetArea)
# Adding a pushbutton to the dock widget
mybtn = QtWidgets.QPushButton("This is a dock
widget")
dockWidget.setWidget(mybtn)
# Adding the dock widget to the main window
mymainWindow.addDockWidget(QtCore.Qt.LeftDockWidget
Area, dockWidget)
# Checking if the dock widget is floating
if dockWidget.isFloating():
print("Dock widget is floating")
print('-'*50)
else:
print("Dock widget is docked")
print('-'*50)
# Connecting to the allowedAreasChanged signal
dockWidget.allowedAreasChanged.connect(lambda
myallowedAreas: print("Allowed areas changed to",
myallowedAreas))
# Connecting to the dockLocationChanged signal
dockWidget.dockLocationChanged.connect(lambda
myarea: print("Dock location changed to", myarea))
# Connecting to the featuresChanged signal
dockWidget.featuresChanged.connect(lambda
myfeatures: print("Features changed to",
myfeatures))
# Connecting to the topLevelChanged signal
dockWidget.topLevelChanged.connect(lambda
mytopLevel: print("Top level changed to",
mytopLevel))
# Connecting to the visibilityChanged signal
dockWidget.visibilityChanged.connect(lambda
myvisible: print("Visibility changed to",
myvisible))
# Setting the dock widget floating
dockWidget.setFloating(True)
mymainWindow.show()
sys.exit(myapp.exec_())
Output
Conclusion
In this section, we got an in-depth understanding of many
container widgets offered by Qt Designer. Readers now have
a good understanding of the features and capabilities of
each widget as well as how to customize them to design
aesthetically pleasing and user-friendly interfaces.
Readers specifically learned about what container widgets
are and how they work, the different types of container
widgets, how to use container widgets to create layouts and
how to customize the appearance of container widgets. Moreover the readers also learned about signal slot
connections, how to connect signals that widgets within
container widgets send to slots and how to use layout managers to create the layouts we want.
To ensure that readers have a firm understanding of
container widgets in Qt Designer, this section also featured
practical examples to remember the concept.