Python Graphical Interface

Insights of Input Widget in QT Designer

A.I Hub
38 min readSep 24, 2024
Image By Author

Mastering user input elements in PyQt5 is essential for building interactive and intuitive applications. The Combo Box provides a simple yet powerful way to offer users multiple choices from a dropdown, while the Font Combo Box enhances customization by allowing dynamic font selection. For direct user input, the Line Edit is a clean, efficient tool for short text entries, and the Text Edit expands on that with rich text support. The Plain Text Edit simplifies this further, perfect for larger blocks of plain text. Precision input is made easy with the Spin Box and Double Spin Box, which let users control numerical values effortlessly. Date and time management is streamlined with the Date Time Edit, allowing accurate, user friendly data input. For more interactive, real-time adjustments, the Dial, QScrollBar and QSlider give users hands-on control over settings and values. Finally, the Key Sequence Edit offers a unique way to capture and define keyboard shortcuts, adding a layer of personalization and functionality to any application. Together, these widgets form the foundation of a user centric, professional grade interface.

Table of Content

  • Introduction
  • Combo box
  • Font combo box
  • Line edit
  • Text edit
  • Plain text edit
  • Spin box
  • Double spin box
  • Date time edit
  • Dial
  • QScrollBar
  • QSlider
  • Key sequence edit

Introduction

Input widgets for PyQt5 are necessary because they provide

users with an approach to input data into PyQt5 applications.

As they allow user interaction and data input, these widgets

are an essential component of creating a Graphical User

Interface for an application.

There are different ways to input data into the input widgets

provided by PyQt5, including text input, number input,
date/time input, and drop-down list selection. The developer

may easily create a user-friendly interface and collect data
from the user thanks to these widgets. Additionally, input
widgets are a crucial component of modern applications
since they let users enter and manipulate data in various
ways.

Different input widgets of Qt Designer

Combo Box

The combination of button and popup list is QComboBox widget.

Users can choose an option from a drop-down list of options
using the QComboBox widget in PyQt5. It is a frequently used
widget for choosing items from a list. We can manually enter items or use a model to fill out the QComboBox widget. Along
with text items, icons may also be displayed. Drop-down lists
with different properties and options can be created using
PyQt5’s QComboBox which is a component of the PyQt5.QtWidgets
package. The ability to make the widget editable, set the
current item, set the maximum number of visible items and
the option to control the insertion policy are some
noteworthy properties and options.

Important properties

Let us go over some important properties.

editable

This property will determine whether the QComboBox object can
be edited by the user or not. The default value is False.

Image depicting editable property of QComboBox in Qt Designer

currentText

The current text displayed in the QComboBox object is returned

using this property.

Image depicting currentText property of QComboBox in Qt

Designer

currentIndex

The default value is -1, and this property will return the index

of the current item selected in the QComboBox object.

Image depicting currentIndex property of QComboBox in Qt

Designer

maxVisibleItems

The maximum number of items to be displayed in the drop-

down lists of the QComboBox object can be set with the help of

the above property. The default value is 10.

Image depicting maxVisibleItems property of QComboBox in Qt
Designer

maxCount

Using this property, the maximum number of items to be

added to the QComboBox object can be set. The default value is

2147483647.

Image depicting maxCount property of QComboBox in Qt Designer

insertPolicy

User can set the policy where items are to appear in the

QComboBox object. The default value is InsertAtBottom.

Image depicting insertPoilcy property of QComboBox in Qt

Designer

sizeAdjustPolicy

The rules policy can be set using this property for the

QComboBox object to adjust its size when the list items change.

Image depicting sizeAdjustPolicy property of QComboBox in Qt
Designer

minimumContentsLength

We can determine the fitting of the minimum number of
characters into the QComboBox object. The default value is 0.

Image depicting minimumContentsLength property of QComboBox
in Qt Designer

iconSize

The icon size to be displayed in the QComboBox object can be
set using this property.

Image depicting iconSize property of QComboBox in Qt Designer

duplicatesEnabled

This Boolean property will determine whether duplicates are

enabled in the QComboBox object. The default value is set to
False.

Image depicting duplicatesEnabled property of QComboBox in Qt
Designer

Frame

When set to True, the QComboBox object draws itself inside a
frame, else draws itself without any frame.

Image depicting frame property of QComboBox in Qt Designer

modelColumn

Using this property, we can set the column of the model
used for populating theQComboBox object. The default value is
0.

Image depicting modelColumn property of QComboBox in Qt
Designer

Important Methods

  • addItem(text[,userData = None]): Using this method, the

    items will be added to the list of existing items in the

    QComboBox object with the given text and optional userData
    argument.
  • addItems(texts): This method will add a list of strings in

    the given texts to the QComboBox object.
  • clear(): This method will remove all items from the

    QComboBox object.
  • count(): This method will return the number of items in

    the QComboBox object.
  • currentText(): This method will return the current Text

    of the QComboBox object.
  • currentIndex(): This method will return the current Item

    index in the QComboBox object.
  • setItemText(index,Text): Using this method, the text of an

    item is changed at a specified index in the QComboBox

    object.

Important Signals

  • activated(index): This signal is emitted when an item in

    the QComboBox object is activated, either by using the

    keyboard to select or by clicking on it. The signal

    carries an argument index as a parameter, which is the

    index of the activated item.
  • currentIndexChanged(index): This signal is emitted

    whenever the QComboBox’s object current index changes.

    The new index is carried by the signal as an argument

    index.
  • highlighted(index): This signal is emitted when a
    QComboBox’s object item is highlighted, either by hovering
    the mouse over it or by using the keyboard to navigate
    to it. The index of the highlighted item is the argument
    index that is carried by the signal.

Now, we shall see an example of the QComboBox widget.

Details of file names
Qt Designer file: ComboBox/combobox_eg1.ui

Consider the following code of run_combobox_eg1.py:

import sys
from PyQt5.QtWidgets import QMainWindow,
QApplication
from combobox_eg1 import *
class MyComboBox(QMainWindow):
def __init__(self):
super().__init__()
self.myui = Ui_MainWindow()
self.myui.setupUi(self)

# adding items to the QComboBox object
self.myui.comboBox.addItems(["Orange",
"Papaya", "Banana"])
# setting the current index to 1
self.myui.comboBox.setCurrentIndex(1)

# inserting the item at index position 0 of
QComboBox widget
self.myui.comboBox.insertItem(0, "Mango")

# display of all the items of QComboBox
widget
for mycount in
range(self.myui.comboBox.count()):
print("Current Index is: " +
str(mycount) + " and the text is: " +
self.myui.comboBox.itemText(mycount))

# connecting the activated and
currentIndexChanged signals to the corresponding
slot methods
self.myui.comboBox.activated.connect(self.myactivat
ed)

self.myui.comboBox.currentIndexChanged.connect(self
.mycurrentIndexChanged)

self.show()

def myactivated(self, myindex):
self.myui.mylbl2.setText("Item Activated
is: " + self.myui.comboBox.currentText())

def mycurrentIndexChanged(self, myindex):
self.myui.mylbl3.setText("Index is: " +
str(myindex) + " & Text is: " +
self.myui.comboBox.currentText())

if __name__=="__main__":
app = QApplication(sys.argv)
w = MyComboBox()
w.show()
sys.exit(app.exec_())

Output

Output of ComboBox/run_combobox_eg1.py
  • the Current Index was set to 1 before
    inserting the item Mango, that is why it displayed Papaya in
    the QComboBox widget to the user.
  • we can view the output when the item
    Orange is selected.
Output When Orange text is selected in

ComboBox/run_combobox_eg1.py

Font Combo Box

In PyQt5, a QFontComboBox widget is a combobox that enables

users to select a font family from a list of system fonts. The

currentFontChanged() signal is sent when a font is selected from

a drop-down list of font family names displayed by the
widget. Along with two QToolButtons for bold and italic
formatting and a QComboBox for adjusting font size, QFontComboBox
is frequently used in toolbars.

Important properties

Let us go over some important properties now.

writingSystem

The writing system of the fonts to be displayed in the QFontComboBox object is held using this property.

Image depicting writingSystem property of QFontComboBox in Qt
Designer

fontFilters

This property will hold the font filters that limit the available

font families in the QFontComboBox object.

Image depicting fontFilters property of QFontComboBox in Qt
Designer

currentFont

This property will hold the currently selected font in the

QFontComboBox object.

Image depicting currentFont property of QFontComboBox in Qt
Designer

Important Methods

  • setCurrentFont(QFont): This method will set the currently

    selected font in the QFontComboBox object.
  • setFontFilters(FontFilters): This method will set the font

    filters used to limit the available font families in the

    QFontComboBox object.
  • setWritingSystem(WritingSystem): This method will set the

    writing system of the fonts to be displayed in the
    QFontComboBox object.

Important signals

Let us now check an important signal.

currentFontChanged(QFont)

This signal is emitted when the currently selected font in the

QFontComboBox object changes. A QFont object is taken as a parameter representing the newly selected font.
Now, we shall see an example of the QFontComboBox widget.

Details of file names
Qt Designer file: FontComboBox/fontcombobox_eg1.ui

Consider the following code of run_fontcombobox_eg1.py:

import sys
from PyQt5.QtWidgets import QMainWindow,
QApplication, QFontComboBox
from fontcombobox_eg1 import *
class MyFontComboBox(QMainWindow):
def __init__(self):
super().__init__()
self.myui = Ui_MainWindow()
self.myui.setupUi(self)

# setting the font filters which are used
to limit the available font families of
QFOntComboBox object
self.myui.fontComboBox.setFontFilters(QFontComboBox
.NonScalableFonts)

# Connecting the currentFontChanged signal
of QFOntComboBox object to the myfontchanged slot

self.myui.fontComboBox.currentFontChanged.connect(s
elf.myfontchanged)
self.show()

def myfontchanged(self, myfont):
self.myui.mylb2.setText("Current font
changed to:" + myfont.family())
if __name__=="__main__":
app = QApplication(sys.argv)
w = MyFontComboBox()
w.show()
sys.exit(app.exec_())

Output

Output of FontComboBox/run_fontcombobox_eg1.py

Line Edit

One of the most commonly used single-line text editors of Qt

Designer is QLineEdit widget. It is frequently used to display

text or to accept text input from users. Various properties,

including font, input mask, placeholder text and so on, can

be changed. Additionally, it offers signals like editingFinished

and textChanged that are emitted when a user interacts with
the widget.

Important properties

Let us go over some important properties now.

inputMask

This property defines a string that specifies a validation input

mask. A valid input format is defined by the mask, such as

any phone number, IP Address, date and so on. An empty
string is returned if no mask is set.

Masked characters and their meanings
Image depicting inputMask property of QLineEdit in Qt Designer

Text

QLineEdit’s object is held using this property. The default

value is an empty string.

Image depicting text property of QLineEdit in Qt Designer

maxLength

The maximum allowed length of the text in the QLineEdit
object is set using this property.

Image depicting maxLength property of QLineEdit in Qt Designer

frame

If checked, the QLineEdit object will be drawn itself inside a

frame.

Image depicting frame property of QLineEdit in Qt Designer

echoMode

This property will decide how the text entered in the QLineEdit

object will be displayed to the user.

Image depicting echoMode property of QLineEdit in Qt Designer

cursorPosition

The current cursor position will be held for the QLineEdit
object. The default value is 0.

Image depicting cursorPosition property of QLineEdit in Qt

Designer

alignment

Using this property, the alignment of QLineEdit object is held

where we can align both horizontal and vertical alignment.

Image depicting alignment property of QLineEdit in Qt Designer

dragEnabled

This property allows the user to press and move the mouse
inside the QLineEdit object. When enabled, it allows the dragging of its contents.

Image depicting deagEnabled property of QLineEdit in Qt

Designer

readOnly

This property is disabled by default and indicates that text

inside the QLineEdit object is readOnly. The user cannot edit

the text but can copy or drag and drop the text.

Image depicting readOnly property of QLineEdit in Qt Designer

placeholderText

We can set and display the placeholder text in the QLineEdit

object when it is empty and not focused.

Image depicting placeholderText property of QLineEdit in Qt

Designer

cursorMoveStyle

We can set the way or movement style of the cursor in the

QLineEdit object.

Image depicting cursorMoveStyle property of QLineEdit in Qt
Designer

clearButtonEnabled

This property will indicate whether the QLineEdit object will

have a clear button when it is not empty. It is disabled by
default.

Image depicting clearButtonEnabled property of QLineEdit in Qt
Designer

Important Methods

  • setText(arg__1): Using this method, the text is set in the

    QLineEdit object to the specified argument string.
  • setValidator(arg__1): The input validator for the QLineEdit

    object is set using this method. The validator
    parameter arg__1 is a QValidator instance or one of its
    subclasses. The input conforms to a specified format

    ensured by the validator.
  • setInputMask(inputMask): An input mask is set for the

    QLineEdit object using this method. The input format is

    specified by the inputMask argument, which is a string.
  • setFont(arg__1): The font is set using this method to

    display the text in the QLineEdit object to the specified

    argument arg__1. This is an instance of the QFont object.
  • setEchoMode(arg__1): The display mode of the text entered
    into the QLineEdit object is set to the specified argument arg__1 (EchoMode).
  • setAlignment(flag): This method will set text alignment in
    the QLineEdit object as per alignment constants.
  • clear(): This method will remove the text from the

    QLineEdit object.
  • setMaxLength(arg__1): This method will set the maximum

    allowed length of the text in the QLineEdit object to the

    specified argument arg__1 of type int.
  • setReadOnly(arg__1): The read-only status of the QLineEdit
    object is set to the specified Read Only Boolean value
    arg__1. If Read Only is set as True, the user cannot
    modify the text in the QLineEdit object.

Important Signals

  • textEdited(): This signal is emitted whenever the text is

    modified by the user, including additions or deletions

    in the QLineEdit object.
  • textChanged(): This signal is emitted whenever any

    QLineEdit object text is changed, including changes

    made programmatically.
  • editingFinished(): This signal is emitted when the user

    completes editing the text in the QLineEdit object by
    pressing the Enter key or leaving the widget.
  • returnPressed(): This signal is emitted by pressing the

    Enter key while editing the text in the QLineEdit object.
  • selectionChanged(): This signal is emitted when the

    selected text in the QLineEdit object is changed.
  • cursorPositionChanged(): This signal is emitted when the

    cursor is moved and its position is changed in the
    QLineEdit object.

Now, we shall see an example of the QLineEdit widget.

Details of file names
Qt Designer file: LineEdit/lineedit_eg1.ui

Consider the following code of run_lineedit_eg1.py:

import sys
import re
from PyQt5.QtWidgets import QMainWindow,
QApplication, QMessageBox
from PyQt5.QtGui import QFont
from lineedit_eg1 import *
class MyLineEdit(QMainWindow):
def __init__(self):
super().__init__()
self.myui = Ui_MainWindow()
self.myui.setupUi(self)

# LineEdit1 -------------------------------
---------------------------------------

# Set the maximum number of characters that
can be entered
self.myui.mylineEdit_1.setMaxLength(10)

self.myui.mylineEdit_1.setFont(QFont("Calibri",16))

self.myui.mylineEdit_1.setPlaceholderText("Enter
username")

# LineEdit2 -------------------------------
---------------------------------------

self.myui.mylineEdit_2.setPlaceholderText("Enter password")
self.myui.mylineEdit_2.setEchoMode(self.myui.myline
Edit_2.Password)

# LineEdit3 -------------------------------
---------------------------------------

self.myui.mylineEdit_3.setPlaceholderText("Enter
email @ is must")
# Connecting the textChanged signal to a
custom function

self.myui.mylineEdit_3.editingFinished.connect(self
.myvalidate_email)

# LineEdit4 -------------------------------
---------------------------------------

self.myui.mylineEdit_4.setInputMask("+99_99999_9999
9")

# LineEdit5 -------------------------------
---------------------------------------
self.myui.mylineEdit_5.setText("Only Read
Only Text")
self.myui.mylineEdit_5.setReadOnly(True)
# LineEdit6 -------------------------------
---------------------------------------

self.myui.mylineEdit_6.textChanged.connect(self.myt
extchanged)


self.show()

def myvalidate_email(self):
# Regex for valid email addresses
myemail_regex = re.compile(r"[^@]+@[^@]+\.
[^@]+")
# Getting the text from the QLineEdit
widget
myemail = self.myui.mylineEdit_3.text()
# Checking if the email address is valid
if not myemail_regex.match(myemail):
# Set the input method to invalid if
the email address is not valid

self.myui.mylineEdit_3.setStyleSheet("border: 1px solid red")
# Displaying an error message
QMessageBox.warning(self, "Error!",
"Email address is invalid")

# focusing on the LineEdit if wrong
email id is entered
self.myui.mylineEdit_3.setFocus()
else:
# Set the input method to valid if the
email address is valid

self.myui.mylineEdit_3.setStyleSheet("border: 1px
solid green")

def mytextchanged(self, mytext):
print("Changed contents: "+ mytext)

if __name__ == "__main__":
app = QApplication(sys.argv)
screen = MyLineEdit()
screen.show()
sys.exit(app.exec_())

Output

Default output for LineEdit/run_lineedit_eg1.py

Case 1 — When LineEdit1 is focused on entering the username

with max length as 10 for LineEdit/run_lineedit_eg1.py.

Output for Case-1 of LineEdit/run_lineedit_eg1.py.

Case 2 — When LineEdit2 is focused and user is required to

enter the password for LineEdit/run_lineedit_eg1.py.

Output for Case-2 of LineEdit/run_lineedit_eg1.py.

Case 3 — When email id entered is wrong, then message is

popped up in LineEdit3 for LineEdit/run_lineedit_eg1.py.

Output for Case-3 of LineEdit/run_lineedit_eg1.py.

Case 4 — When email id entered is correct in LineEdit3 for

LineEdit/run_lineedit_eg1.py.

Output for Case-4 of LineEdit/run_lineedit_eg1.py.

Case 6 — When user enters hithere text, textchanged event of

LineEdit6 is triggered to a method for the display of text to
the console for LineEdit/run_lineedit_eg1.py.

Output for Case-6 of LineEdit/run_lineedit_eg1.py.

Text Edit

The PyQt5 widget QTextEdit offers a multi-line text area for

editing and displaying documents in plain text or HTML. It

includes undo and redo capability and extensive text
formatting options like bold, italic and underlining. It can be
utilized to develop simple text editors, email clients and
other programs that require the ability to edit and display
text.

Important properties

Let us check some important properties now.

autoFormatting

This property will determine enabling of automatic

formatting features like text completion, spelling correction,

and so on, of the QTextEdit object. The default value is
AutoNone. For enabling all automatic formatting, the user may
select AutoAll.

Image depicting autoFormatting property of QTextEdit in Qt

Designer

tabChangeFocus

On pressing the Tab key, this property determines whether

the focus will be changed to the next widget or a tab
character is inserted into the QTextEdit object. The default
value is False.

Image depicting tabChangeFocus property of QTextEdit in Qt
Designer

documentTitle

This property will hold the document title parsed from the

text. For a newly created empty document, this property
contains an empty string by default.

Image depicting documentTitle property of QTextEdit in Qt

Designer

undoRedoEnabled

This property will determine whether functionality, like undo

and redo, is enabled. The default value is True.

Image depicting undoRedoEnabled property of QTextEdit in Qt
Designer

lineWrapMode

This property will hold the mode of line wrap and determine

the way the text will be wrapped when it reaches the end of
the line. The default mode is WidgetWidth, and the words will
be wrapped at the right edge of the QTextEdit object.

Image depicting lineWrapMode property of QTextEdit in Qt

Designer

lineWrapColumnOrWidth

This property will determine the position width in pixels or

columns depending on the selection of warp mode in which

text will be wrapped in the QTextEdit object.

Image depicting lineWrapColumnOrWidth property of QTextEdit
in Qt Designer

readOnly

This property, when set to True, will make the text in the

QTextEdit object read-only, that is, it cannot be edited. The

default value is False.

Image depicting readOnly property of QTextEdit in Qt Designer

html

An HTML interface is provided for the text of the QTextEdit
object.

Image depicting html property of QTextEdit in Qt Designer

overwriteMode

This property will overwrite the existing text with a text
entered by the user when set. The default value is False,
indicating that the new text will not overwrite the existing
text.

Image depicting overwriteMode property of QTextEdit in Qt

Designer

tabStopWidth

This property will hold the width of tabStop in pixels where the

default value is 80 pixels.

Image depicting tabStopWidth property of QTextEdit in Qt

Designer
tabStopDistance

This property will hold the distance of tabStop in pixels.

acceptRichText

This property will determine whether richtext, such as HTML,

is accepted in the QTextEdit object. The default value is True.

Image depicting acceptRichText property of QTextEdit in Qt

Designer

cursorWidth

This property will specify the cursor width in pixels and the

default value is 1.

Image depicting cursorWidth property of QTextEdit in Qt Designer

textInteractionFlags

This property will determine how the QTextEdit object will
interact with mouse and keyboard events.

Image depicting textInteractionFlags property of QTextEdit in Qt
Designer

placeholderText

This property will hold the placeholder text displayed in the

QTextEdit object when it is not focused and empty.

Image depicting placeholderText property of QTextEdit in Qt

Designer

Important Methods

  • append(text): The specified argument text of type string

    is added to the end of the current document in the

    QTextEdit object.
  • insertHtml(text): The specified argument text of type

    string is inserted and formatted as HTML into the
    QTextEdit object at the current cursor position.
  • insertPlainText(text): The specified argument text of type

    string is inserted as plain text into the QTextEdit object

    at the current cursor position.
  • setCurrentFont(f): The selected text font or text at the

    cursor position is changed to argument f, a QFont object.
  • clear(): This method will delete all the text in the

    QTextEdit object.
  • setPlainText(text): This method will replace the current

    text in the QTextEdit object with the specified text
    formatted as plain text.
  • setHtml(text): This method will replace the current text

    in the QTextEdit object with the specified text formatted

    by providing an HTML interface. The interpretation of

    input text will be as rich text in HTML format.

Just prepend set to all the properties discussed, followed by

the parameters. This will add to the list of methods. We have

discussed only a few methods.

Important Signals

  • textChanged(): This signal is emitted when the text in the

    QTextEdit object is changed.
  • undoAvailable(b): This signal is emitted when the

    availability of an undo operation changes. Parameter b
    is a Boolean value indicating whether an undo
    operation is available.

    redoAvailable(b): This signal is emitted when the
    availability of a redo operation changes. Parameter b is
    a Boolean value indicating whether a redo operation is
    available.
  • copyAvailable(b): This signal is emitted when the
    availability of a copy operation changes. Parameter b is
    a Boolean value indicating whether a copy operation is
    available.

Now, we shall see an example of the QTextEdit widget.

Details of file names
Qt Designer file: TextEdit/textedit_eg1.ui

Consider the following code of run_textedit_eg1.py:

import sys
import re
from PyQt5.QtWidgets import
QMainWindow,QApplication, QFontDialog
from textedit_eg1 import *
class MyTextEdit(QMainWindow):
def __init__(self):
super().__init__()
self.myui = Ui_MainWindow()
self.myui.setupUi(self)

self.myui.mybtn1.clicked.connect(self.my_btn1)

self.myui.mybtn2.clicked.connect(self.my_btn2)

self.myui.mybtn3.clicked.connect(self.my_btn3)

# replacing the text of TextEdit object
with 'Hello'
self.myui.textEdit.setText("Hello")

self.show()

def my_btn1(self):
# prompting the user to select the font
family, font style, size
myfont, imok = QFontDialog.getFont()
# on pressing Ok replacing the text in the
TextEdit object with the selected font
if imok:

self.myui.textEdit.setCurrentFont(myfont)

def my_btn2(self):
# replacing the text of TextEdit object
with plain text on button click
self.myui.textEdit.setPlainText("Hi
Friends!\nWelcome to study PyQt5 textEdit widget")

def my_btn3(self):
# replacing the text of TextEdit object
with text formatted by providing an html interface
on button click
self.myui.textEdit.setHtml("<font
color='green' size='7'>Hi Friends!\nHello</font>")

if __name__ == "__main__":
app = QApplication(sys.argv)
screen = MyTextEdit()
screen.show()
sys.exit(app.exec_())

Output

Default output of TextEdit/run_textedit_eg1.py

Case 1 — First text inside the QTextEdit is selected and then

selecting the font, font style and Size from QFontDialog.

Case1 output of TextEdit/run_textedit_eg1.py

Case 2 — The text inside the QTextEdit is changed as per
choice selected from QFontDialog Box.

Case2 output of TextEdit/run_textedit_eg1.py

Case 3 — On clicking Setting Plain Text button.

Case3 output of TextEdit/run_textedit_eg1.py

Case 4 — On clicking Setting Html Text button.

Case4 output of TextEdit/run_textedit_eg1.py

Plain Text Edit

QPlainTextEdit widget is a multi-line text editor that makes it

simple to view and edit plain text in PyQt5. Line numbers,
text wrapping, undo/redo, and copy/paste are among the few

features it offers. The setPlainText() method can be used to
style the text and the toPlainText() method can be used to
retrieve it. If there is an application requirement to display

plain text content, then we need to use the QPlainTextEdit
widget. Otherwise, if there is a requirement to display
formatted text, use QTextEdit widget.

Important properties

Maximum properties are similar to that of the Text Edit
widget. The other extra properties are explained in the
following section.

plainText

This property will hold the plain text displayed in the
QPlainTextEdit object. The text displayed in the QPlainTextEdit

can be either get or set using this property. By default, this
object contains an empty string.

Image depicting plainText property of QPlainTextEdit in Qt

Designer

maximumBlockCount

This property will determine the maximum number of blocks

visible in the QPlainTextEdit object. An unlimited number of

blocks can be contained by the QPlainTextEdit object if the
value is set as 0 or -1.

Image depicting maximumBlockCount property of QPlainTextEdit
in Qt Designer

backgroundVisible

This property determines whether the palette background is
visible outside of the document area. The default value is
False.

Image depicting backgroundVisible property of QPlainTextEdit in
Qt Designer

centerOnScroll

This property will determine whether the cursor will be

centered on the screen when QPlainTextEdit object is scrolled.

The default value is False. The text will always be seen in
the middle of the widget if the value is True, which centers
the view. When the value is set to False, the view scrolls
normally and the text moves up or down as the widget is

scrolled.

Image depicting centerOnScroll property of QPlainTextEdit in Qt
Designer

Important Methods

  • appendPlainText(text): This method will add the given text

    to the end of the QPlainTextEdit object.
  • insertPlainText(text): This method will insert the given

    text at the current cursor position of the QPlainTextEdit

    object.
  • setPlainText(text): This method will set the QPlainTextEdit

    object content with the given text.
  • clear(): This method will delete all the QPlainTextEdit

    object content.
  • toPlainText(text): This method will return QPlainTextEdit

    object content.

Important Signals

  • textChanged(): This signal is emitted when the text in the

    QPlainTextEdit object is changed.
  • cursorPositionChanged(): This signal is emitted whenever

    the cursor position in the QPlainTextEdit object changes.
  • blockCountChanged(newBlockCount): This signal is emitted

    when the number of blocks, that is, lines in the

    QPlainTextEdit object changes.
  • selectionChanged(): This signal is emitted by a
    QPlainTextEdit object when its selection changes.

Now, we shall see an example of the QPlainTextEdit widget.

Details of file names
Qt Designer file: PlainTextEdit/plaintextedit_eg1.ui

Consider the following code of run_plaintextedit_eg1.py:

import sys
import re
from PyQt5.QtWidgets import
QMainWindow,QApplication, QFontDialog
from plaintextedit_eg1 import *
class MyPlainTextEdit(QMainWindow):
def __init__(self):
super().__init__()
self.myui = Ui_MainWindow()
self.myui.setupUi(self)
# setting the placeholder text in the
QPlainTexEdit object

self.myui.plainTextEdit.setPlaceholderText("Kindly
enter any plain text")

self.myui.plainTextEdit.textChanged.connect(self.my
textchanged)

self.myui.plainTextEdit.cursorPositionChanged.conne
ct(self.my_on_cursor_position_changed)

self.myui.mybtn.clicked.connect(self.my_btn1)
# Connecting the blockCountChanged signal
to the my_on_block_count_changed slot

self.myui.plainTextEdit.blockCountChanged.connect(s
elf.my_on_block_count_changed)
self.show()
def my_btn1(self):
# appending the text to QPlainTextEdit object

self.myui.plainTextEdit.appendPlainText("Some Text
is Added")

def mytextchanged(self):
self.myui.mylbl.setText("QPlainTextEdit
signal is emitted")

# Method for the cursorPositionChanged signal
def my_on_cursor_position_changed(self):
mycursor =
self.myui.plainTextEdit.textCursor()
print("Cursor position is changed to column
no.:", mycursor.position())

# Method for the blockCountChanged signal
def my_on_block_count_changed(self,
my_new_block_count):
print("Block count changed to:",
my_new_block_count)

if __name__ == "__main__":
app = QApplication(sys.argv)
screen = MyPlainTextEdit()
screen.show()
sys.exit(app.exec_())

Output

Default output of PlainTextEdit/run_plaintextedit_eg1.py

Case 1 — On clicking Add Text button, textChanged and

cursorPositionChanged signal is being emitted.

Case1 output of PlainTextEdit/run_plaintextedit_eg1.py

Case 2 — On again clicking Add Text button, all the three

signals textChanged, cursorPositionChanged and blockCountChanged
signal are emitted.

Case2 output of PlainTextEdit/run_plaintextedit_eg1.py

Spin Box

A Spin Box widget in PyQt5 allows the user to choose a value
by pressing the Up and Down arrow keys of the keyboard or
by clicking the Up and Down button. The values can be
typed directly by the user and are displayed in the textbox.
This widget supports integer numbers and may find a

convenient way to choose within a specified range.

Important properties

Some important properties are discussed in the next section.

wrapping

When the QSpinBox object hits or reaches its minimum or

maximum value, this property determines whether or not it

should wrap around. To enable wrapping, set it to True; to

disable it, set it to False default value.

Image depicting wrapping property of QSpinBox in Qt Designer

frame

This property will determine whether QSpinBox object should

have a frame or not. The default value is set as checked.

Image depicting frame property of QSpinBox in Qt Designer

alignment

This property will set the content alignment within the
QSpinBox object.

Image depicting alignment property of QSpinBox in Qt Designer

readOnly

This property will allow QSpinBox object to readOnly when set to

True.

Image depicting readOnly property of QSpinBox in Qt Designer

buttonSymbols

This property will set the symbol in the up and down button
of QSpinBox object.

Image depicting buttonSymbols property of QSpinBox in Qt

Designer

specialValueText

This property will set and display the special value text in the

QSpinBox object when the value is set to minimum or
maximum of the range and the object is in special value
mode.

Image depicting specialValueText property of QSpinBox in Qt
Designer

accelerated

This property will decide whether the QSpinBox object value
changes should be accelerated.

Image depicting accelerated property of QSpinBox in Qt Designer

correctionMode

This property will determine the behavior of the QSpinBox

object if the user enters an invalid value.

Image depicting correctionMode property of QSpinBox in Qt

Designer

keyboardTracking

This property will determine the tracking of keyboard inputs
in the QSpinBox object.

Image depicting keyboardTracking property of QSpinBox in Qt
Designer

showGroupSeparator

This property will determine whether the QSpinBox object

should display a group separator.

Image depicting showGroupSeparator property of QSpinBox in Qt
Designer

suffix

This property will set a string that will be appended to the
current value of the QSpinBox object.

Image depicting suffix property of QSpinBox in Qt Designer

prefix

This property will set a string that will be prepended to the
current value of the QSpinBox object.

Image depicting prefix property of QSpinBox in Qt Designer

minimum

This property will set the minimum value that can be entered
in the QSpinBox object.

Image depicting minimum property of QSpinBox in Qt Designer

maximum

This property will set the maximum value that can be

entered in the QSpinBox object.

Image depicting maximum property of QSpinBox in Qt Designer

singleStep

This property will set the step size for incrementing or
decrementing the value in the QSpinBox object.

Image depicting singlestep property of QSpinBox in Qt Designer

value

This property will set or return the current value of the
QSpinBox object.

Image depicting value property of QSpinBox in Qt Designer

displayIntegerBase

This property will set the base for displaying the value in the

QSpinBox object.

Image depicting displayIntegerBase property of QSpinBox in Qt
Designer

Important Methods

  • setMinimum(min): This method will set the minimum value
    that can be entered in the QSpinBox object where the min

    parameter is the minimum value. The default value is

    0.
  • setMaximum(max): This method will set the maximum value
    that can be entered in the QSpinBox object where the max parameter is the maximum value. The default value is
    99.
  • setRange(min,max): This method will set the minimum and
    maximum values for the QSpinBox object in one call.

    Here, the min parameter is the minimum value and the

    max parameter is the maximum value.
  • setValue(val): This method will set the current value of
    the QSpinBox object where the val parameter is the value
    to be set.
  • value(): This method will return the current value of the

    QSpinBox object.
  • cleanText(): This method will return the text of the

    QSpinBox object, excluding prefix/suffix or
    trailing/leading whitespace.
  • setDisplayIntegerBase(base): The base for displaying the

    value of the QSpinBox object is set by this method.

Important signals

Let us discuss an important signal.

valueChanged(arg__1)

This signal is emitted when the value of the QSpinBox object

changes either by entering a new value or spinning the
wheel. The arg__1 parameter is an integer type representing
the new value of the QSpinBox object.
Now, we shall see an example of the QSpinBox widget.

Details of file names
Qt Designer file: SpinBox/spinbox_eg1.ui

Consider the following code of run_spinbox_eg1.py:

import sys
import re
from PyQt5.QtWidgets import
QMainWindow,QApplication
from spinbox_eg1 import *
class MySpinBoxEdit(QMainWindow):
def __init__(self):
super().__init__()
self.myui = Ui_MainWindow()
self.myui.setupUi(self)
# Setting the initial value
self.myui.spinBox.setValue(0)
# Setting the minimum value
self.myui.spinBox.setMinimum(-2)
# Setting the maximum value
self.myui.spinBox.setMaximum(2)

# signal is emitted when the QSpinBox
object value changes

self.myui.spinBox.valueChanged.connect(self.my_valu
echange)
# signal is emitted on button click and
connected to the method my_btn1

self.myui.mybtn.clicked.connect(self.my_btn1)
self.show()
def my_btn1(self):
# Setting the range of values
self.myui.spinBox.setRange(-3, 3)
def my_valuechange(self,myval):
self.myui.mylbl2.setText("My current value
is:"+str(myval))

if __name__ == "__main__":
app = QApplication(sys.argv)
screen = MySpinBoxEdit()
screen.show()
sys.exit(app.exec_())

Output

Default output of SpinBox/run_spinbox_eg1.py

Case 1 — When Up button of spin box widget is clicked once,
then its valueChanged signal is triggered.

Case1 output of SpinBox/run_spinbox_eg1.py

Case 2 — Here, Up button of spin box widget is clicked many
times. The maximum value of the widget is 2.

Case2 output of SpinBox/run_spinbox_eg1.py

Case 3 — Here, Down button of spin box widget is clicked
many times. The minimum value of the widget is -2.

Case3 output of SpinBox/run_spinbox_eg1.py

Case 4 — Here, Set Range button is clicked and the maximum
and minimum value is set as 3 and -3. Down button of spin
box widget is clicked many times. The minimum value of the
widget is -3.

Case4 output of SpinBox/run_spinbox_eg1.py

Case 5 — Now, Up button of spin box widget is clicked many
times. The maximum value of the widget is 3.

Case5 output of SpinBox/run_spinbox_eg1.py

Double Spin Box

This QDoubleSpinBox class in PyQt5 allows the user to choose a

value by either using the up or down arrow keys from the
keyboard or directly entering the text field. It is a spinbox
widget for supporting double type values.

Important properties

The properties of the Double Spin Box widget are similar to
that of the Spin Box Widget. It has a decimals property
instead of displayIntegerBase and properties of minimum,
maximum, value and singleStep is of type double.

decimals

This property will specify the number of decimal places to be

displayed in the QDoubleSpinBox object, that is, precision.

Image depicting decimals property of QDoubleSpinBox in Qt

Designer

Important methods

All the methods of the QSpinBox widget discussed are almost

similar to that of the QDoubleSpinBox widget, except for one
method. Instead of the setDisplayIntegerBase() method, this
widget has the setDecimals() method.

setDecimals(prec)

This method will set the number of decimal places to be
displayed in the QDoubleSpinBox object. Here, prec is an integer
argument that represents the number of decimal places to
be displayed.

Important signals

Let us discuss an important signal.

valueChanged(arg__1)

This signal is emitted when the value of the QDoubleSpinBox

object changes either by entering a new value or spinning
the wheel. The arg__1 parameter is of double type,
representing the new value of the QDoubleSpinBox object.

Now, we shall see an example of the QDoubleSpinBox widget.

Details of file names
Qt Designer file: DoubleSpinBox/doublespinbox_eg1.ui

Consider the following code of run_doublespinbox_eg1.py:

import sys
import re
from PyQt5.QtWidgets import
QMainWindow,QApplication
from doublespinbox_eg1 import *
class MyDoubleSpinBoxEdit(QMainWindow):
def __init__(self):
super().__init__()
self.myui = Ui_MainWindow()
self.myui.setupUi(self)

# Setting the initial value of
QDoubleSpinBox object
self.myui.doubleSpinBox.setValue(0.10)
# Setting the minimum value of
QDoubleSpinBox object
self.myui.doubleSpinBox.setMinimum(-1.10)
# Setting the maximum value of
QDoubleSpinBox object
self.myui.doubleSpinBox.setMaximum(1.10)

# Setting the step value to 0.2 of
QDoubleSpinBox object
self.myui.doubleSpinBox.setSingleStep(0.2)

# signal is emitted when the QDoubleSpinBox
object value changes

self.myui.doubleSpinBox.valueChanged.connect(self.m
y_valuechange)
# signal is emitted on button click and
connected to the method my_btn1

self.myui.my_btn.clicked.connect(self.my_btn1)
self.show()
def my_btn1(self):
# Setting the range of values of
QDoubleSpinBox object
self.myui.doubleSpinBox.setRange(-2.10,
2.10)

def my_valuechange(self,myval):
# setting the label text when valueChanged
signal is emitted
self.myui.mylbl2.setText("My current value
is:"+str(myval))

if __name__ == "__main__":
app = QApplication(sys.argv)
screen = MyDoubleSpinBoxEdit()
screen.show()
sys.exit(app.exec_())

Output

Default output of DoubleSpinBox/run_doublespinbox_eg1.py

Case 1 — When Up Button of double spin box widget is clicked

once, then valueChanged signal is emitted.

Case1 output of DoubleSpinBox/run_doublespinbox_eg1.py

Case 2 — Up Button of double spin box widget is clicked many

times and it reached its maximum value. The maximum
value of the widget is set as 1.10.

Case2 output of DoubleSpinBox/run_doublespinbox_eg1.py

Case 3 — Down Button of double spin box widget is clicked

many times and it reached its maximum value. The
minimum value of the widget is set as -1.10

Case3 output of DoubleSpinBox/run_doublespinbox_eg1.py

Case 4 — “Set Range of type double button” is clicked and the

maximum and minimum range is set as 2.10 and -2.10. Down
button of the double spin box widget is clicked many times till it
reached the minimum value. The minimum value of the
widget is set as -2.10.

Case4 output of DoubleSpinBox/run_doublespinbox_eg1.py

Case 5 — Up button of double spin box widget is clicked many

times till it reached the maximum value. The maximum
value of the widget is set as 2.10.

Case5 output of DoubleSpinBox/run_doublespinbox_eg1.py

Date/Time Edit

The QDateTimeEdit widget in the PyQt5 library will allow the

user to select and edit date and time values. Numerous
display formats, such as date-only, time-only and date-time displays, are supported by QDateTimeEdit. The user has the
choice of selecting values from a calendar pop-up or entering
them manually into the widget. A useful set of controls for
adjusting values is also included by the widget, including up
and down buttons for incrementing and decrementing the
date and time. Additionally, QDateTimeEdit provides various

input validation and user interaction features, including read-only displays, the ability to step through values
incrementally, minimum and maximum dates and times and
so on.

Important properties

Let us discuss some important properties now.

date

This property will hold the date that is currently set in the

widget. The default value is set to the date of 1st Jan 2000.
The object is QDate.

Image depicting date property of QDateTimeEdit in Qt Designer

time

This property will hold the time that is currently set in the
widget. The default value contains the time of 00:00:00 and 0 milliseconds. The object is QTime.

Image depicting time property of QDateTimeEdit in Qt Designer

maximumDateTime

This property will hold the maximum date and time values

that are allowed to be set for the QDateTimeEdit object. The

minimumDateTime is adjusted on setting this property. Only this

property can be set to a valid QDateTime value. The end of 9999

CE is the latest date that is accepted. The default value is

23:59:59 and 999 milliseconds for the time.

Image depicting maximumDateTime property of QDateTimeEdit
in Qt Designer

minimumDateTime

This property will hold the minimum date and time values

that are allowed to be set for the QDateTimeEdit object. The

maximumDateTime is adjusted on setting this property. Only this

property can be set to a valid QDateTime value. The start of

100CE is the earliest date and time that is accepted. The
default value is 14th Sep 1752 for the date and 00:00:00 and 0
milliseconds for the time.

Image depicting minimumDateTime property of QDateTimeEdit
in Qt Designer

maximumDate

This property will hold the maximum date of the QDateTimeEdit
object. The default value is the end of 9999 CE.

Image depicting maximumDate property of QDateTimeEdit in Qt
Designer

minimumDate

This property will hold the minimum date of the QDateTimeEdit
object. The default value is 14th Sep, 1752.

Image depicting minimumDate property of QDateTimeEdit in Qt
Designer

maximumTime

This property will hold the maximum time of the QDateTimeEdit
object. The default value is 23:59:59 and 999 milliseconds.

Image depicting maximumTime property of QDateTimeEdit in Qt
Designer

minimumTime

This property will hold the minimum time of the QDateTimeEdit
object. The default value is 00:00:00 and 0 milliseconds.

Image depicting minimumTime property of QDateTimeEdit in Qt
Designer

currentSection

This property will hold the section of date/time of the

QDateTimeEdit object, which has a focus such as year, month,
day, hour, minute or second.

Image depicting currentSection property of QDateTimeEdit in Qt
Designer

displayFormat

This property will set the date and time format in the
QDateTimeEdit object. The default format is dd-MM-yyyy HH:mm.

Image depicting displayFormat property of QDateTimeEdit in Qt
Designer

calendarPopup

When a user clicks on the QDateTimeEdit widget, this property
determines whether or not a calendar pop-up is shown.

When the pop-up is enabled, the user can choose a date
from the calendar and the QDateTimeEdit widget will update
accordingly.

Image depicting calendarPopup property of QDateTimeEdit in Qt
Designer

currentSectionIndex

The QDateTimeEdit widget’s currently active section index is

returned by this property.

Image depicting currentSectionIndex property of QDateTimeEdit
in Qt Designer

timeSpec

The QDateTimeEdit widget’s time specification, which
establishes the time zone and whether daylight saving time
is used, is set by this property. Local time, Coordinated
Universal Time or a particular time zone can all be

specified as the time specification.

Image depicting timeSpec property of QDateTimeEdit in Qt

Designer

Important Methods/Signals

  • dateTime(): This method will return the currently

    selected date and time as a QDateTime object.
  • setMaximumDateTime(dt): This method will set the maximum
    date and time which can be set in the QDateTimeEdit
    object by taking the QDateTime object as a parameter.
  • dateChanged(date): This signal is emitted when the date in

    the QDateTimeEdit object changes. Here, the date

    argument is a QDate object representing the new date.
  • dateTimeChanged(dateTime): This signal is emitted when the

    date and time in the QDateTimeEdit object is changed.
    Here, the dateTime argument is a QDateTime object
    representing the new date and time.
  • timeChanged(time): This signal is emitted when time in the

    QDateTimeEdit object is changed. Here, the time argument
    is a QTime object representing the new time.

Now, we shall see an example of the QDateTimeEdit widget.

Details of file names
Qt Designer file: DateorTimeEdit/datetimeedit_eg1.ui

Consider the following code of run_datetimeedit_eg1.py:

import sys
from PyQt5.QtWidgets import
QMainWindow,QApplication
from PyQt5.QtCore import *
from datetimeedit_eg1 import *
class MyDateTimeEdit(QMainWindow):
def __init__(self):
super().__init__()
self.myui = Ui_MainWindow()
self.myui.setupUi(self)

# setting the date and time for the widget

self.myui.dateTimeEdit.setDateTime(QDateTime.curren
tDateTime())

# Setting the display format for the
QDateTimeEdit widget

self.myui.dateTimeEdit.setDisplayFormat("yyyy-MM-dd
hh:mm:ss")
# Setting the calendar popup to be enabled

self.myui.dateTimeEdit.setCalendarPopup(True)
# Setting the maximum and minimum dates
that can be selected

self.myui.dateTimeEdit.setMaximumDate(QDate.current
Date().addYears(1))

self.myui.dateTimeEdit.setMinimumDate(QDate.current
Date().addDays(-365))
# Connecting the signals to their
respective handlers

self.myui.dateTimeEdit.timeChanged.connect(self.my_
handle_time_changed)

self.myui.dateTimeEdit.dateChanged.connect(self.my_
handle_date_changed)
# signal is emitted on button click and
connected to the method my_btn1

self.myui.mybtn.clicked.connect(self.my_btn1)

self.show()
def my_btn1(self):
self.myui.mylbl2.setText("Displaying Date
and Time to: " +
str(self.myui.dateTimeEdit.dateTime()))

def my_handle_time_changed(self, time):
self.myui.mylbl2.setText("Time changed to:
" + time.toString())
def my_handle_date_changed(self, date):
self.myui.mylbl2.setText("Date changed to:
" + date.toString())
if __name__ == "__main__":
app = QApplication(sys.argv)
screen = MyDateTimeEdit()
screen.show()
sys.exit(app.exec_())

Output

Default output of DateorTimeEdit/run_datetimeedit_eg1.py

Case 1 — When date is changed, dateChanged signal is emitted.

Case1 output of DateorTimeEdit/run_datetimeedit_eg1.py

Case 2 — When time is changed, timeChanged signal is emitted.

Case2 output of DateorTimeEdit/run_datetimeedit_eg1.py

Case 3 — When Set Date and Time button is clicked, then Date

and Time is displayed.

Case3 output of DateorTimeEdit/run_datetimeedit_eg1.py

Dial

PyQt5, a Python library for building graphical user interfaces,

has a QDial widget. A circular dial called QDial can be rotated

to choose a value from a specified range. It provides a
convenient method for the user to change a numerical value,
like a brightness or volume setting. QDial‘s features, including
the value range, the number of notches, the dial’s

appearance and how it behaves to drags and clicks, can all
be changed. QDial behaves similarly to a slider because it
derives from QAbstractSlider.

Important properties

The properties of QAbstractSlider are discussed in the next
section.

minimum

This property will set the minimum value of the QDial object.
The default value is 0.

Image depicting minimum property of QDial in Qt Designer

maximum

This property will set the maximum value of the QDial object.
The default value is 99.

Image depicting maximum property of QDial in Qt Designer

singleStep

This property will hold the step size for single steps of the

QDial object. The default value is 1. If this property is set as 5,
then on rotating the QDial object, the ‘value’ property will be
changed by 5.

Image depicting singleStep property of QDial in Qt Designer

pageStep

This property will hold the step size for page steps of the

QDial object. The default value is 10. If this property is set as

10, then on clicking the background of the QDial object, the
‘value’ property will be changed by 10.

Image depicting pageStep property of QDial in Qt Designer

value

This property will hold the current value of the QDial object
and is always between the minimum and maximum values. It
will be updated when the QDial object is clicked or rotated.
The default value is 0.

sliderPosition

This property will hold the current value of the QDial object.

Image depicting sliderPosition property of QDial in Qt Designer

tracking

This property will determine whether the dial’s value is

updated continuously while it is moved or only when the
mouse button is released. When tracking is enabled, the
valueChanged signal is continuously emitted and the value of the dial is updated as it is dragged.

Image depicting tracking property of QDial in Qt Designer

orientation

This property will specify the orientation of the QDial object

either vertically or horizontally.

Image depicting orientation property of QDial in Qt Designer

invertedAppearance

This property will specify whether the QDial object
appearance is inverted. The default value is False.

Image depicting invertedAppearance property of QDial in Qt

Designer

invertedControls

This property will specify whether the QDial object controls
are inverted. The default value is False.

Image depicting invertedControls property of QDial in Qt

Designer

Properties of QDial

The properties of QDial are discussed in the next section.

wrapping

This property will determine whether wrapping is enabled or

not. When enabled, the arrow on the QDial object can be
pointed in any direction. If the arrow is disabled, it can only
go to the top of the QDial object, if it moves to the bottom of
the QDial object, it is clamped to the end of the valid range of
values closest to it.

Image depicting wrapping property of QDial in Qt Designer

notchTarget

The target number of pixels between notches is held by this

property. The number of pixels QDial tries to place in between

the notch is known as the notchTarget. The default value is 3.7
pixels.

Image depicting notchTarget property of QDial in Qt Designer

notchesVisible

This property will determine whether the QDial object should

display notches or not.

Image depicting notchesVisible property of QDial in Qt Designer

Important methods/signals

If we prepend the set word with all QDial properties, that is,

wrapping, notchTarget, and notchesVisible, then we will get

methods (setwrapping(on), setnotchTarget(target),

setNotchesVisible(visible)). The QDial object will constantly emit

a valueChanged() signal as the slider is being moved.
Now, we shall see an example of a QDial widget.

Details of file names
Qt Designer file: Dial/dial_eg1.ui

Consider the following code of run_dial_eg1.py:

import sys
from PyQt5.QtWidgets import
QMainWindow,QApplication
from dial_eg1 import *
class MyDateTimeEdit(QMainWindow):
def __init__(self):
super().__init__()
self.myui = Ui_MainWindow()
self.myui.setupUi(self)
# set the min and max values of the dial
self.myui.dial.setRange(0, 100)
# default value is set to 30
self.myui.dial.setValue(30)
# the dial will move by increment of 1
self.myui.dial.setNotchTarget(1.0)
# valueChanged signal will be emitted
continuously as the dial is rotated
self.myui.dial.setTracking(True)
# the dial value will wrap around from the
max value to the min value and vice versa
self.myui.dial.setWrapping(True)

# connecting the valueChanged signal of the
dial to my_labelupdate method

self.myui.dial.valueChanged.connect(self.my_labelup date)

self.show()
def my_labelupdate(self, myval):
self.myui.mylbl1.setText("Value is: " +
str(myval))
if __name__ == "__main__":
app = QApplication(sys.argv)
screen = MyDateTimeEdit()
screen.show()
sys.exit(app.exec_())

Output

Output of Dial/run_dial_eg1.py

QScrollBar

  • For horizontal scrollbar, class is QScrollBar.
  • Contains properties of QAbstractSlider. Here, the

    default value of orientation is Horizontal, and the

    invertedControls property is checked.
  • For vertical scrollbar, class is QScrollBar
  • Contains properties of QAbstractSlider. Here, the

    default value of orientation is Vertical and the inverted Controls property is checked.

Now, we shall see an example of the QScrollBar widget.

Details of file names
Qt Designer file : Scrollbar/scrollbar_eg1.ui

Consider the following code of run_scrollbar_eg1.py:

import sys
from PyQt5.QtWidgets import QApplication,
QMainWindow, QTextEdit
from PyQt5.QtCore import Qt
from scrollbar_eg1 import *
class MyScrollbar(QMainWindow):
def __init__(self):
super().__init__()
self.myui = Ui_MainWindow()
self.myui.setupUi(self)

# signal is emitted on button click and
connected to the method my_btn1

self.myui.btn1.clicked.connect(self.my_btn1)

self.myui.btn2.clicked.connect(self.my_btn2)

self.myui.btn3.clicked.connect(self.my_btn3)
# Set some initial text to show in the text edit
self.myui.mytextEdit.setPlainText("PyQt5 is
a Python binding for the Qt GUI toolkit, which
allows developers to create desktop applications
with rich graphical user interfaces. It provides
access to a wide range of Qt classes and functions,
making it possible to create applications that are
portable across different platforms, including
Windows, Linux, and macOS. PyQt5 also includes
tools for creating custom widgets and interfaces,
and supports advanced features like multithreading,
network programming, and OpenGL. Overall, PyQt5 is
a powerful and flexible framework for building
desktop applications using Python. Tkinter is a
built-in Python GUI (Graphical User Interface)
toolkit that provides developers with a set of
widgets, such as buttons, labels, text boxes, and
menus, for building desktop applications. It is
based on the Tcl/Tk GUI toolkit and provides a
simple and easy-to-use interface for creating
cross-platform applications that run on Windows,
Linux, and macOS. With Tkinter, developers can
create event-driven applications that respond to
user input, such as mouse clicks and keyboard
events. It also provides tools for creating custom
dialogs, message boxes, and other types of pop-up
windows.Tkinter supports a wide range of features,
such as internationalization, drag-and-drop
support, and support for various font types and
colors. It also provides tools for creating
animated graphics, simple games, and multimedia
applications.Overall, Tkinter is a powerful and
flexible toolkit for creating desktop applications
using Python. Its simplicity and cross-platform
support make it a popular choice for developers who
want to create simple GUI applications without the
overhead of more complex frameworks.")

def my_btn1(self):
# set the text wrap mode to NoWrap

self.myui.mytextEdit.setLineWrapMode(QTextEdit.NoWrap)
def my_btn2(self):
# set the text wrap mode to WidgetWidth

self.myui.mytextEdit.setLineWrapMode(QTextEdit.WidgetWidth)
def my_btn3(self):
# set the text wrap mode to FixedPixelWidth

self.myui.mytextEdit.setLineWrapMode(QTextEdit.FixedPixelWidth)
if __name__ == '__main__':
myapp = QApplication(sys.argv)
mywidget = MyScrollbar()
mywidget.show()
sys.exit(myapp.exec_())

Output

Default output of Scrollbar/run_scrollbar_eg1.py

Case 1 — When No wrap Mode button is clicked.

Case1 output of Scrollbar/run_scrollbar_eg1.py

Case 2 — When WidgetWidth button is clicked.

Case2 output of Scrollbar/run_scrollbar_eg1.py

Case 3 — When FixedPixelWidth button is clicked.

Case3 output of Scrollbar/run_scrollbar_eg1.py

QSlider

  • For both Vertical and Horizontal slider, the class is

    QSlider.

Important properties

It comprises the properties of QAbstractSlider. The other

properties are as follows.

tickPosition

This property will control the tick position small marks
placed across the slider for indicating specific values in the
QSlider object. The default value is NoTicks.

Image depicting tickPosition property of QSlider in Qt Designer

tickInterval

This property will hold the value interval and not the pixel
interval between tickmarks, that is, spacing between the
ticks in the QSlider object. The default value is 0.

Image depicting tickInterval property of QSlider in Qt Designer

Important Methods/Signals

  • valueChanged(): This signal is emitted when the value of

    the QSlider object is changed.
  • sliderPressed(): This signal is emitted when the user will

    start to drag the QSlider object.
  • sliderMoved(): This signal is emitted when the user drags

    the QSlider object.
  • sliderReleased(): This signal is emitted when the user

    releases the QSlider object.

Important properties

The properties and methods/signals are similar to the ones

discussed in Horizontal slider.

Now, we shall see an example of QScrollBar widget.

Details of file names

Consider the following code of run_slider_eg1.py:

import sys
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QApplication,
QGridLayout, QLabel, QSlider, QWidget
from PyQt5.QtGui import QFont
class MySliderWidget(QWidget):
def __init__(self):
super().__init__()
# Creating a label object for the
horizontal slider
myhlabel = QLabel('Horizontal')
myhlabel.setAlignment(Qt.AlignCenter)
# Creating a horizontal slider object
myhslider = QSlider(Qt.Horizontal)
myhslider.setFocusPolicy(Qt.NoFocus)
myhslider.setRange(0, 100)
myhslider.setValue(30)
myhslider.setTickInterval(10)

myhslider.setTickPosition(QSlider.TicksBelow)
# Create a label object for the vertical
slider
myvlabel = QLabel('Vertical')
myvlabel.setAlignment(Qt.AlignCenter)

# Creating a vertical slider
myvslider = QSlider(Qt.Vertical)
myvslider.setFocusPolicy(Qt.NoFocus)
myvslider.setRange(0, 100)
myvslider.setValue(40)
myvslider.setTickInterval(10)

myvslider.setTickPosition(QSlider.TicksLeft)
# Creating a label object to show the value
of the horizontal slider
myhvalue = QLabel(str(myhslider.value()))
myhvalue.setAlignment(Qt.AlignCenter)

# creating a font object for myhvalue and
myvvalue
myfont = QFont()
myfont.setPointSize(12)
myfont.setBold(True)
myhvalue.setFont(myfont)
# Creating a label object to show the value
of the vertical slider
myvvalue = QLabel(str(myvslider.value()))
myvvalue.setAlignment(Qt.AlignCenter)
myvvalue.setFont(myfont)
# Creating a grid object layout to organize
the widgets
mygrid = QGridLayout()
mygrid.setSpacing(10)
# Adding the horizontal slider and label
object to the grid
mygrid.addWidget(myhlabel, 0, 0)
mygrid.addWidget(myhslider, 1, 0)
mygrid.addWidget(myhvalue, 2, 0)
# Adding the vertical slider and label
object to the grid
mygrid.addWidget(myvlabel, 0, 1)
mygrid.addWidget(myvslider, 1, 1)
mygrid.addWidget(myvvalue, 2, 1)
# Connecting the valueChanged signal of
myhslider object to its label obj myhvalue
myhslider.valueChanged.connect(lambda
value: myhvalue.setText(str(value)))
# Connecting the valueChanged signal of
myvslider object to its label obj myvvalue
myvslider.valueChanged.connect(lambda
value: myvvalue.setText(str(value)))
self.setLayout(mygrid)
self.setGeometry(400, 400, 400, 400)
self.setWindowTitle('My Sliders and Labelseg')
self.show()
if __name__ == '__main__':
myapp = QApplication(sys.argv)
myslider_widget = MySliderWidget()
sys.exit(myapp.exec_())

Output

Output of Slider/run_slider_eg1.py

Key Sequence Edit

This widget in PyQt5 will allow the user to select a keyboard

shortcut, that is, to input a QKeySequence. The recording starts
when the widget gets the user’s attention and concludes one

second after the last key is released.

Important properties

Let us discuss an important property now.

keySequence

This property is used to set the key sequence that
QKeySequenceEdit object represents.

Image depicting keySequence property of QKeySequenceEdit in
Qt Designer

Important Methods/Signals

  • setKeySequence(keySequence): This method will set the key

    sequence displayed in the QKeySequenceEdit object. The

    parameter keySequence is a string that represents a key

    sequence.
    keySequenceChanged
  • (keySequence): This signal is emitted
    when the key sequence for a shortcut changes. The

    parameter keySequence is a string that represents a key

    sequence.

Consider the following code of run_keysequenceedit_eg1.py:

import sys
from PyQt5.QtWidgets import QApplication,
QMainWindow, QKeySequenceEdit
from PyQt5.QtGui import QKeySequence
from PyQt5.QtCore import Qt
class MyKeySequence(QMainWindow):
def __init__(self):
super().__init__()
# Create a QKeySequenceEdit widget
self.my_key_edit = QKeySequenceEdit(self)

self.my_key_edit.setKeySequence(QKeySequence(Qt.CTR
L + Qt.Key_H))

self.my_key_edit.keySequenceChanged.connect(self.my
_handle_key_sequence_changed)
self.setCentralWidget(self.my_key_edit)
# Slot method called when the key sequence is
changed
def my_handle_key_sequence_changed(self,my_key_seq):
print(f"My New key sequence:
{my_key_seq.toString()}")
if __name__ == '__main__':
myapp = QApplication(sys.argv)
mywidget = MyKeySequence()
mywidget.show()
myapp.exec_()

Output

Output of KeySequenceEdit/run_keysequenceedit_eg1.py

Conclusion

--

--

A.I Hub
A.I Hub

Written by A.I Hub

We writes about Data Science | Software Development | Machine Learning | Artificial Intelligence | Ethical Hacking and much more. Unleash your potential with us

No responses yet