Python Graphical Interface
In Qt Designer, display widgets are the cornerstone of any visually engaging and informative application. Whether you are looking to present static text, dynamic data or live feedback to users, these widgets transform your interface into an interactive hub. The Label widget is your go-to for simple yet effective text and image displays, bringing clarity to your interface. For more dynamic content, the Text Browser enables rich text viewing with hyperlinks and HTML support, making it perfect for manuals or web based content. The Calendar Widget brings sleek and intuitive date selection, ideal for scheduling apps or any date-related functionality. When it comes to numerical displays, the LCD Number widget captures attention with its futuristic digital aesthetic, giving real-time feedback with style. And let’s not forget the Progress Bar, an essential tool for visually tracking task completion or loading states, keeping users informed and engaged as processes unfold. These display widgets are not just functional but they elevate the user experience by providing essential visual cues in a clean and professional manner.
Table of Content
- Introduction to the display widgets in Qt Designer
- Label
- Text browser
- Calendar widget
- LCD number
- Progress bar
Introduction to the Display Widgets in Qt Designer
This is the final section on Qt Designer in which we
will deal with some display widgets of Qt Designer.
We shall discuss the importance of each input widget one by
one.
Label
A QLabel widget in PyQt5 is a display widget used to display
text, an image, or any animated GIF on a GUI form page. It
can be used to inform the user, by displaying PlainText,
RichText or an image.
Important properties
Let us check some important properties now.
text
This property will hold the QLabel object text.
textFormat
This property will hold the QLabel object text format. Default
format selected is AutoText.
pixmap
This property will hold the QLabel object pixmap.
scaledContents
This property will hold whether QLabel object will scale its
contents to fill all the available space.
alignment
This property will hold QLabel object content alignment.
wordWrap
This property will determine whether QLabel object will wrap
the text at necessary word breaks. The default value is
False.
margin
This property will hold the width of the margin separation
between the innermost pixel of frame and outermost pixel of
content surrounding the QLabel object content.
indent
This property will hold the QLabel object text indent in pixels.
openExternalLinks
This property will specify whether the QLabel object should
automatically open external links using openUrl() instead of
linkActivated() signal emitting. The default value is False.
Designer
textInteractionFlags
This property will describe how the QLabel object should
respond to user interaction if it displays text.
Designer
buddy
This property will hold the QLabel object buddy widget. A
widget is connected to another widget using the buddy
mechanism so that they can be used in combination.
Important Methods/Signals
- setText(arg__1): This method will set the text of the QLabel
object to the specified argument arg__1, which is of type
string. - setPixmap(arg__1): This method will set the image or
pixmap to the QLabel object to the specified argument
arg__1, which is of QPixmap object. - setTextInteractionFlags(flags): This method will set the
text interaction flags of QLabel object, and the flags will
determine how the user will interact with the text in
the QLabel object. - linkActivated(link): This signal is emitted when the link
URL of the activated link in QLabel object is activated. - linkHovered(link): This signal is emitted when the mouse
hovers over a link in QLabel object.
Now, we shall see an example of QLabel widget.
Consider the following code of run_label_eg1.py:
import sys
from PyQt5.QtWidgets import QMainWindow,
QApplication
from PyQt5.QtGui import QPixmap
from label_eg1 import *
class MyLabel(QMainWindow):
def __init__(self):
super().__init__()
self.myui = Ui_MainWindow()
self.myui.setupUi(self)
# displaying rich text
self.myui.mylbl1.setText("Displaying plain text.")
# displaying rich text
self.myui.mylbl2.setText("<font
color='green'>Displaying rich text.</font>")
self.myui.lineEdit.setText("Buddy with Label")
# setting the buddy property of the label
to the LineEdit object
self.myui.mylbl2.setBuddy(self.myui.lineEdit)
# displaying image
self.myui.mylbl3.setPixmap(QPixmap("myimage.jpg"))
self.show()
if __name__ == "__main__":
app = QApplication(sys.argv)
screen = MyLabel()
screen.show()
sys.exit(app.exec_())
Output
In this example, we have used horizontal and vertical lines,
which are class lines. These lines are typically used as
separators to visually divide sections of the GUI page. They
can be used to group related widgets together, making the
form more organized and easier to navigate.
Text Browser
A rich text browser with hypertext navigation capabilities is
offered by PyQt5’s QtextBrowser class. The user can interact
with the text by clicking on links and selecting the text and
it is used to display formatted text, including images and
links. The read-only QtextBrowser class extends the QtextEdit
class and offers more functionality for displaying and
navigating hypertext. It supports a number of text types,
including plain text, HTML and Markdown. Cascading Style
Sheets and inline HTML tags can be used to style the
text.
Important properties
It contains properties of QtextEdit. The other properties are
discussed in the sections.
Source
The URL of the current document displayed in the QtextBrowser
object can be set or obtained using this property. Both the
source() method and setSource() method can be used to get
and set it.
searchPaths
This property will hold the search paths used by the
QtextBrowser object to search for resources such as images
and documents.
Designer
openExternalLinks
This property determines whether links that lead to external
URLs should be opened within QTextBrowser object or as a
separate application. The default value is False.
Qt Designer
openLinks
If the user attempts to activate links using the mouse or
keyboard, QTextBrowser should automatically open those links,
according to this property. The default value is True.
Designer
Important Methods/Signals
- isBackwardAvailable(): If the backward history is available
to navigate in the QTextBrowser object, then this method
will return True; else will return False. - isForwardAvailable(): If the forward history is available to
navigate in the QTextBrowser object, then this method will
return True; else will return False. - anchorClicked(arg_ _1): This signal is emitted when a
hyperlink is clicked in the QTextBrowser object. - sourceChanged(arg_ _1): This signal is emitted when the
source of the QTextBrowser object changes.
Now, we shall see an example of QTextBrowser widget.
Consider the following code of run_textbrowser_eg1.py:
import sys
from PyQt5.QtWidgets import
QMainWindow,QApplication
from PyQt5.QtGui import QTextCursor
from textbrowser_eg1 import *
class MyTextBrowser(QMainWindow):
def __init__(self):
super().__init__()
self.myui = Ui_MainWindow()
self.myui.setupUi(self)
self.myui.textBrowser.setOpenExternalLinks(True)
self.myui.textBrowser.setStyleSheet('font-
size: 24px;')
self.myui.btn.clicked.connect(self.my_btn_clickme)
self.show()
def my_btn_clickme(self):
self.myui.textBrowser.moveCursor(QTextCursor.Start)
self.myui.textBrowser.append('Displaying
Bolloywood movies list')
self.myui.textBrowser.append('<a
href=https://en.wikipedia.org/wiki/List_of_Hindi_fi
lms_of_2023>Bollywood Movies 2023</a>')
if __name__ == "__main__":
app = QApplication(sys.argv)
screen = MyTextBrowser()
screen.show()
sys.exit(app.exec_())
Output
Case — When Click Me button is clicked, then the text will be
appended in the text browser widget. User may click the
hyperlink text Bollywood Movies 2023 and if connected to
internet, then it will navigate to that web page.
button is clicked
Calendar Widget
The PyQt5 widget QCalendarWidget offers a monthly calendar
view and allows users to select a date. Events,
appointments and other time-based information can be
displayed using the above widget. Numerous customization
options are available for the widget, including choosing the
first day of the week, specifying a minimum and maximum
date range and enabling or disabling certain dates.
Programmatic retrieval of the selected date or range is also
possible or through signals emitted by the widget.
Important properties
Let us explore some important properties now.
selectedDate
This property view will hold the currently selected date,
which must be within the dateRange specified by the minimumDate
and maximumDate property of QCalendarWidget object.
Designer
minimumDate
The minimum date of the currently specified date range of
QCalendarWidget object is held by this property.
Designer
maximumDate
The maximum date of the currently specified date range of
QCalendarWidget object is held by this property.
Qt Designer
firstDayOfWeek
This property will get or set the first day of the week in the
QCalendarWidget object.
Qt Designer
gridVisible
This property will get or set the visibility in the grid lines in
the QCalendarWidget object.
Designer
selectionMode
This property will hold the selection type the user can make
in the QCalendarWidget object. The user will be unable to select
the dates on NoSelection or can select a date within the
minimum and maximum allowed dates on SingleSelection.
Qt Designer
horizontalHeaderFormat
This property will get or set the format of the horizontal
header.
QCalendarWidget in Qt Designer
verticalHeaderFormat
This property will get or set the format of the vertical header.
QCalendarWidget in Qt Designer
navigationBarVisible
This property will determine whether the navigation bar is to
be displayed or not in the QCalendarWidget object.
QCalendarWidget in Qt Designer
dateEditEnabled
This property determines whether the date edit popup is
enabled or not.
Qt Designer
dateEditAcceptDelay
This property specifies the time delay default value is 1500
in milliseconds the date edit will remain active following the
most recent user input. The popup is closed once the time
has elapsed, thus accepting the date specified in the date
edit.
QCalendarWidget in Qt Designer
Important Methods/Signals
Just prepend the word set in the properties of the above
widget and we will get the required methods. We will discuss
an important signal in this section.
selectionChanged()
This signal is emitted when the user changes the currently
selected date in the QCalendarWidget object.
Now, we shall see an example of QCalendarWidget.
Consider the following code of run_calendarwidget_eg1.py:
import sys
from PyQt5.QtWidgets import
QMainWindow,QApplication
from calendarwidget_eg1 import *
class MyCalendarWidget(QMainWindow):
def __init__(self):
super().__init__()
self.myui = Ui_MainWindow()
self.myui.setupUi(self)
# Connect the calendar's selectionChanged
signal to the update_label method
self.myui.calendarWidget.selectionChanged.connect(s
elf.my_display_date)
self.show()
# Define a method to set the label object text
with the selected date
def my_display_date(self):
self.myui.mylbl.setText('Selected date is:
{}'.format(self.myui.calendarWidget.selectedDate().
toString()))
if __name__ == "__main__":
app = QApplication(sys.argv)
screen = MyCalendarWidget()
screen.show()
sys.exit(app.exec_())
Output
Case — When any date is selected from the QCalendarWidget
object, the selected date will be displayed in the label
widget.
date is selected from the QCalendar widget object
LCD Number
The PyQt5 widget QLCDNumber shows a numerical value in a
seven-segment LCD display. In GUI forms, it is commonly
used to display numerical data, such as sensor, timer and
other measurements. As a QFrame subclass, QLCDNumber offers a
number of methods and properties to control the LCD
display’s appearance and behavior.
Important properties
Let us check some important properties now.
smallDecimalPoint
This property will hold the decimal point style of QLCDNumber
object. The default value is False, indicating that the
decimal point is displayed as a large dot. When set to True,
the decimal point is displayed as a small dot.
Qt Designer
digitCount
This property will set the current number of digits displayed
in the QLCDNumber object. The default value is 5.
Designer
mode
This property will set the current display mode of the
QLCDNumber object which can be hexadecimal, decimal, octal or
binary. The default value is Dec.
segmentStyle
This property will set the style of the QLCDNumber object. Raised
segments filled with background color are produced when
style is Outline filled. Raised segments filled with foreground
color are produced when style is Filled default value. Flat
segments filled with foreground color are produced when
style is Flat.
Designer
value
This property will set the numeric value displayed in the QLCDNumber object. Value can be integer or float value.
intValue
This property will be truncated to the nearest integer to the
current value displayed by the QLCDNumber object.
Important Methods/Signals
display(num)
This method will set the numeric value displayed in the
QLCDNumber object. The parameter num can be of integer or
double type.
Now, we shall see an example of QLCDNumber widget.
Consider the following code of run_lcdnumber_eg1.py:
import sys
from PyQt5.QtWidgets import
QMainWindow,QApplication, QLCDNumber
from lcdnumber_eg1 import *
class MyLCDNumber(QMainWindow):
def __init__(self):
super().__init__()
self.myui = Ui_MainWindow()
self.myui.setupUi(self)
# Set the minimum and maximum values for
the vertical slider
self.myui.verticalSlider.setMinimum(0)
self.myui.verticalSlider.setMaximum(100)
self.myui.verticalSlider.setValue(0)
# change the segment style to flat
self.myui.lcdNumber.setSegmentStyle(QLCDNumber.Flat)
# Connect the slider's valueChanged signal
to the lcd's display slot
self.myui.verticalSlider.valueChanged.connect(self.
myui.lcdNumber.display)
self.show()
if __name__ == "__main__":
app = QApplication(sys.argv)
screen = MyLCDNumber()
screen.show()
sys.exit(app.exec_())
Output
Case — The numeric value in the LCDNumber widget is
displayed when the vertical slider is moved.
slider is moved.
Progress Bar
In PyQt5, the QProgressBar widget is used to display an
operation’s progress. It is often used to display the status of
a task when the user must wait for the operation to finish,
such as a file download or data transfer. The QProgressBar
widget provides a visual indication that displays the
operation’s progress. The progress bar grows in length as
long as the operation progresses. Additionally, the widget
provides a label that may be used to display a message
which describes the operation being performed. A horizontal
or vertical progress bar is provided by the QProgressBar widget.
Important properties
Let us check some important properties now.
minimum
This property will hold the minimum value of the QProgressBar
object. The default value is 0.
Designer
maximum
This property will hold the maximum value of the QProgressBar
object. The default value is 100.
Designer
value
This property will hold the current value of the QProgressBar
object. The default value is 24.
alignment
This property will represent the alignment of the QProgressBar
object. User may choose the options for both horizontal and
vertical alignment.
Designer
textVisible
This property will determine whether QProgressBar object’s
value should be displayed as text or not. The default value is
True.
Designer
orientation
This property will represent the orientation of the QProgressBar
object, which can be set to either horizontal or vertical. The
default value is Horizontal.
Designer
invertedAppearance
This property will determine whether the appearance of
QProgressBar object should be inverted or not. The default
value is False.
Qt Designer
textDirection
This property will have no impact on the horizontal
QProgressBar object and will hold the text reading direction on
vertical QProgressBar object. The default value is TopToBottom.
Designer
format
This property will represent the QProgressBar object’s text
format where %p is replaced by percentage completed, %m for
the total number of steps and %v for the current value. The
default value is %p%.
Important methods/signals
Just prepend the word set in the properties of the above
widget, and we will get the required methods. We have an
important and useful signal for the above widget which is
valueChanged() signal.
valueChanged(value)
This signal is emitted whenever the value in the QProgressBar
object changes programmatically or due to user interaction. The value argument is of type int, which is the new value of
QProgressBar object after the change.
Now, we shall see an example of QProgressBar.
Consider the following code of run_progressbar_eg1.py:
import sys
from PyQt5.QtWidgets import
QMainWindow,QApplication
from progressbar_eg1 import *
class MyProgressBar(QMainWindow):
def __init__(self):
super().__init__()
self.myui = Ui_MainWindow()
self.myui.setupUi(self)
def my_start_counting(self):
self.myui.progressBar.setRange(0, 1000)
self.myui.progressBar.setValue(0)
for i in range(1, 1001):
self.myui.progressBar.setValue(i)
self.myui.mylbl.setText(f"Count No is:
{i}")
QApplication.processEvents() #
processing any pending events for updating the UI
if __name__ == "__main__":
app = QApplication(sys.argv)
myprogress_bar_widget = MyProgressBar()
myprogress_bar_widget.show()
myprogress_bar_widget.my_start_counting()
sys.exit(app.exec_())
Output
There are other widgets which are Graphics View and OpenGL
widget which the reader can explore on their own.
Conclusion
In this section, we have learned about concepts of various
display widgets available in Qt and how to effectively utilize
them to create interactive user interfaces. Through the exploration of various widgets, we have gained knowledge
on how to effectively display static text or images using
labels and along with the ability to customize their font, colour,
alignment and size. Furthermore, we have recognized the
significance of labels in enhancing the visual presentation of
information in a graphical user interface. The TextBrowser
widget has been thoroughly examined, enabling us to grasp
its features for displaying and controlling rich text content.
We have learned how to incorporate hyperlinks, graphics
and formatting choices to create dynamic and interactive
text displays. This knowledge opens up opportunities for
creating engaging and versatile user interfaces. Moreover,
the section delved into adding a calendar widget to our GUI
application. By understanding how to customize its appearance, structure and behavior, we are equipped to
tailor the calendar widget to meet the specific requirements
of our application. The LCDNumber widget has been introduced
as a means to display numerical values, such as counters,
with the added capability of modifying its digit count,
decimal accuracy, look and style. This widget provides a
visually appealing and customizable way to present numeric
data to users. Finally, we explored the ProgressBar widget,
which enables us to visualize the progress of a task or
operation. Understanding how to dynamically update the
progress bar based on our application’s needs allows for
effective feedback and user engagement. Armed with this
knowledge, the user is now equipped to create visually
appealing, interactive and functional graphical user interfaces.