0% found this document useful (0 votes)
52 views302 pages

Python GUI Applications Using PyQt5 _ the Hands-On Guide to Build Apps With Python

The document is a tutorial on creating Python GUI applications using PyQt5, covering installation, basic functionalities, and various widgets. It includes step-by-step examples for opening windows, inserting icons, closing windows, displaying tooltips, and more. The tutorial is structured into several parts, each focusing on different aspects of PyQt5 development, making it suitable for beginners and intermediate users alike.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
52 views302 pages

Python GUI Applications Using PyQt5 _ the Hands-On Guide to Build Apps With Python

The document is a tutorial on creating Python GUI applications using PyQt5, covering installation, basic functionalities, and various widgets. It includes step-by-step examples for opening windows, inserting icons, closing windows, displaying tooltips, and more. The tutorial is structured into several parts, each focusing on different aspects of PyQt5 development, making it suitable for beginners and intermediate users alike.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 302

About the Authors

George W New was received Bachelor of Computer Science from


the American University, and Bachelor of Business Administration
from the American University, USA.

Table of Contents
Contents
About the Authors
Table of Contents
Python GUI Applications using PyQt5
PART 1: Introduction
# 1: PyQt5 Introduction
About PyQt5
About Python
# 2: Install PyCharm
STEP 1. Download
STEP 2. Install
STEP 3. Settings
STEP 4. Create project
STEP 5. Print ‘Hello, World!’
PART 2: PyQt5 Basics
# 1: Opening a window
Example
Description
Results
# 2: Inserting an application icon
Example
Description
Results
# 3: Closing window
Example
Description
Results
# 4: Displaying a tooltip
Example
Description
Results
# 5: Creating a statusbar
Example
Description
Results
# 6: Creating a menubar
Example
Description
Results
# 7: Creating a toolbar
Example
Description
Results
# 8: Centering window
Example
Description
# 9: Displaying date and time
Displaying date
Print current date
Set the date format
Displaying time
Print current time
Set the time format
Displaying date and time
Print current date and time
Set date and time format
Displaying date on statusbar
# 10: Customizing style
Example
Description
Results
PART 3: PyQt5 Layout
# 1: Absolute positioning
Example
Description
Results
# 2: Box layout
Example
Description
Results
# 3: Grid layout
Example
Description
Results
PART 4: PyQt5 Widget
# 1: QPushButton
Example
Description
Results
# 2: QLabel
Example
Description
Results
# 3: QCheckBox
Example
Description
Results
# 4: QRadioButton
Example
Description
Results
# 5: QComboBox
Example
Description
Results
# 6: QLineEdit
Example
Description
Results
# 7: QLineEdit (Advanced)
Example
Description
Results
# 8: QProgressBar
Example
Description
Results
# 9: QSlider & QDial
Example
Description
Results
# 10: QSplitter
Example
Description
Results
# 11: QGroupBox
Example
Description
Results
# 12: QTabWidget
Example
Description
Results
# 13: QTabWidget (Advanced)
Example
Description
Results
# 14: QPixmap
Example
Description
Results
# 15: QCalendarWidget
Example
Description
Results
# 16: QSpinBox
Example
Description
Results
# 17: QDoubleSpinBox
Example
Description
Results
# 18: QDateEdit
Example
Description
Results
# 19: QTimeEdit
Example
Description
Results
# 20: QDateTimeEdit
Example
Description
Results
# 21: QTextBrowser
Example
Description
Results
# 22: QTextBrowser (Advanced)
Example
Description
Results
# 23: QTextEdit
Example
Description
Results
PART 5: PyQt5 Dialog
# 1: QInputDialog
Example
Description
Results
# 2: QColorDialog
Example
Description
Results
# 3: QFontDialog
Example
Description
Results
# 4: QFileDialog
Example
Description
Results
# 5: QMessageBox
Example
Description
Results
PART 6: PyQt5 Signals and slots
# 1: Connecting signal and slot
Example
Description
Results
# 2: Make event handler
Example
Description
Results
# 3: Reimplement event handler
Example
Description
# 4: Reimplemente event handler 2
Example
Description
Results
# 5: User defined signal
Example
Description
PART 7: Examples and Projects
# 1: Creating a simple browser using PyQt5
# 2: Timer Application using PyQt5
# 3: Create Paint Application – PyQt5
Python3
# 4: Building QR Code Generator Application using PyQt5
Python3
# 5: Snake Game - PyQt5
# 6: Age Calculator using PyQt
# 7: Number Guessing Game - PyQt5
# 8: Jumble Word Game - PyQt5
Python3
Conclusion
Python GUI Applications using
PyQt5
PART 1: Introduction
# 1: PyQt5 Introduction
This tutorial deals with the basic features of PyQt5.
The given example codes were written with Python3 and tested
under Windows and macOS.
About PyQt5

PyQt5 is the Python version for Qt5 application


framework. Qt is a powerful cross-platform C++ library
and development tool.
PyQt5 is a collection of Python modules that includes
1000+ such classes.
PyQt5 supports desktop platforms (Windows, Linux,
macOS) and mobile platforms (Android, iOS).
You can get the newest stable version of PyQt5 and
documents at the official website .
PyQt5 developer can choose between GPL and
commercial license. (License FAQ)
According to Riverbankcomputing, PyQt combines the
benefits of the Qt C++ cross-platform application
framework and cross-platform interpreter language
Python.

About Python

Python is a dynamically-typed, object-oriented


programming language.
Python is a high level, multipurpose, cross-platform
interpreter language.
Python is developed for emphasis on code readability and
program productivity.
Python aims at minimalism. One of the most noticeable
features of Python is that it uses indentation instead of
semicolons(;) and parentheses({}).
Python was creaed by Guido van Rossum and first
released in 1991.
Python is currently divided into 2.x and 3.x versions. The
two versions are incompatible; according to the Python
official document, it is recommended for new
programmers to start with Python3.
Python was designed to fix the design flaws of
programming language and to make code writing more
clear.
As a open-source software, Python is maintained by a
large number of voluntary participants.
Python is a very ideal language for those interested in
learning programming language.

# 2: Install PyCharm
PyCharm is the most widely used integrated development
environment (IDE) or development tool for Python development.
Integrated development environment (IDE) includes code editor,
debugger, compiler, interpreter etc. and provides various functions
such as auto-complete and search.
Follow this guide step by step to install PyCharm.
STEP 1. Download
Download the free Community version at JetBrains official
website( Link )

STEP 2. Install
Run the downloaded file.
Choose the install location.
Create desktop shortcut and create association for files with .py
extension.
Choose the Start Menu Folder (or enter a name for new folder) and
click ‘Install’.
The installation begins.
Check the box for “Run PyCharm Community Edition” and finish
installation.
STEP 3. Settings
If there isn’t a particular setting to import, check the bottom box
and click ‘OK’.
Scroll to the end to read the policy and click ‘Accept’.

Decide whether or not to send usage statistics to JetBrains.


Set UI theme.

STEP 4. Create project


Click ‘Create New Project’ for a new project.
Enter the name for your project and click ‘Create’.
STEP 5. Print ‘Hello, World!’
On startup, tip of the day will appear. Click ‘Close’.
Right click on ‘Project’ -> New -> Choose ‘Python file’.

Enter file name and click ‘OK’.


Enter ‘print(‘Hello, World!’)’ in the code editor and press
‘Ctrl+Shift+F10’ to run. This will print the results as follows.

If Python isn’t installed, the following error will appear.


For Python and PyQt5 installation, install Anaconda.
PART 2: PyQt5 Basics

# 1: Opening a window

Let’s pop up a small window like the above.


You can maximize, minimize, or exit the window with the basic
buttons given. You can also move the window around or resize it
with your mouse.
Although these functions actually require a large number of codes,
they are already coded because these functions are widely used in
most applications.

Example
import sys
from PyQt5.QtWidgets import QApplication, QWidget

class MyApp(QWidget):
def __init__(self):
super().__init__()

self.initUI()

def initUI(self):

self.setWindowTitle('My First Application')


self.move(300, 300)
self.resize(400, 200)
self.show()

if __name__ == '__main__':

app = QApplication(sys.argv)
ex = MyApp()
sys.exit(app.exec_())
These lines of codes display a small window on the screen.

Description
import sys
from PyQt5.QtWidgets import QApplication, QWidget
Import the necessary parts. The widgets(classes) that compose the
basic UI elements are included in the PyQt5.QtWidgets module.
You can check out further descriptions about classes included in
QtWidgets at QtWidgets official document .

self.setWindowTitle('My First Application')


self.move(300, 300)
self.resize(400, 200)
self.show()
Here, self refers to MyApp object.
setWindowTitle() method sets the name of the window that appears
on the title bar.
move() method moves the widget to x=300px, y=300px.
resize() method resizes the widget to width 400px, height 200px.
show() method displays the widget on the screen.

if __name__ == '__main__':
__name__ is the internal variable in which the current module’s
name is saved.
If you import a code named ‘moduleA.py’ and run the example
code, __name__ becomes ‘moduleA’.
If you just run the code, __name__ becomes ‘__main__’. Hence
through this single line of code you can see whether the program is
run manually or run through a module.

app = QApplication(sys.argv)
All PyQt5 applications need to create an application object. You
can find further description about QApplication at QApplication
official document .

Results
Figure 3-1. Opening a window.

# 2: Inserting an application icon

Application icon is a small image that will be shown on the left end
of the title bar. Now we’ll see how to display application icon.
First, save the image file(web.png) that you wish to use as the icon
in the folder.

web.png

Example
import sys
from PyQt5.QtWidgets import QApplication, QWidget
from PyQt5.QtGui import QIcon

class MyApp(QWidget):

def __init__(self):
super().__init__()

self.initUI()

def initUI(self):

self.setWindowTitle('Icon')
self.setWindowIcon(QIcon('web.png'))
self.setGeometry(300, 300, 300, 200)
self.show()

if __name__ == '__main__':

app = QApplication(sys.argv)
ex = MyApp()
sys.exit(app.exec_())
A small icon is shown at the left end of the title bar while opening a
new window.

Description
self.setWindowIcon(QIcon('web.png'))
setWindowIcon() method helps set up application icon. Create a
QIcon object for this. Insert the image(web.png) to be displayed on
QIcon().
If the image file is saved in a different folder, input the path as
well.

self.setGeometry(300, 300, 300, 200)


setGeometry() method sets the window’s location and size. The
first two parameters determine the window’s x,y location and the
next two parameters each determine the window’s width and
height.
This method is identical to combining the move() and resize()
methods used in the example for opening window into a single
method.

Results

Figure 3-2. Inserting an application icon.

# 3: Closing window
The easiest way to close a window is to click the ‘X’ button on the
right(Windows) or left(macOS) of the title bar. Now we’ll learn
how to close a window through programming.
We’ll also briefly learn about signal and slot.

Example
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton
from PyQt5.QtCore import QCoreApplication

class MyApp(QWidget):

def __init__(self):
super().__init__()

self.initUI()

def initUI(self):

btn = QPushButton('Quit', self)


btn.move(50, 50)
btn.resize(btn.sizeHint())
btn.clicked.connect(QCoreApplication.instance().quit)

self.setWindowTitle('Quit Button')
self.setGeometry(300, 300, 300, 200)
self.show()

if __name__ == '__main__':
app = QApplication(sys.argv)
ex = MyApp()
sys.exit(app.exec_())
We made the ‘Quit’ button. Now if you click this button, you can
quit the application.

Description
from PyQt5.QtCore import QCoreApplication
Import QCoreApplication class from QtCore module.

btn = QPushButton('Quit', self)


Create a push button. This button(btn) is the instance for
QPushButton class.
Enter the text you wish to be shown on the button at the first
parameter of (QPushButton()), and enter the parent widget in
which the button will be located at the second parameter.
For further details about push button widget, refer to QPushButton
page.

btn.clicked.connect(QCoreApplication.instance().quit)
PIn PyQt5, event processing works with signal and slot
mechanism. If you click (btn), the ‘clicked’ signal will be created.
instance() method restores current instance.
‘clicked’ signal connects to quit()method which quits the
application.
This is how the sender and receiver communicate. In this example,
the sender is the push button(btn) and the receiver is the application
object(app).
Results

Figure 3-3. Making a button for closing the window.

# 4: Displaying a tooltip
Tooltip is a short piece of text that explains a widget’s function.
( QToolTip official document )
We can make tooltip appear for all the elements in the widget.
We’ll use setToolTip() method to make tooltip in widgets.

Example
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton,
QToolTip
from PyQt5.QtGui import QFont

class MyApp(QWidget):

def __init__(self):
super().__init__()

self.initUI()

def initUI(self):

QToolTip.setFont(QFont('SansSerif', 10))
self.setToolTip('This is a <b>QWidget</b> widget')

btn = QPushButton('Button', self)


btn.setToolTip('This is a <b>QPushButton</b> widget')
btn.move(50, 50)
btn.resize(btn.sizeHint())
self.setWindowTitle('Tooltips')
self.setGeometry(300, 300, 300, 200)
self.show()

if __name__ == '__main__':

app = QApplication(sys.argv)
ex = MyApp()
sys.exit(app.exec_())
In this example, we can see tooltips for two PyQt5 widgets. If you
move the cursor to push button(btn) and window(MyApp) widgets,
the set-up text will appear as tooltip.

Description
QToolTip.setFont(QFont('SansSerif', 10))
self.setToolTip('This is a <b>QWidget</b> widget')
First set the font for tooltip. Here we used 10px ‘SansSerif’.
To make tooltip, use setToolTip() method to enter the text you wish
to be displayed.

btn = QPushButton('Button', self)


btn.setToolTip('This is a <b>QPushButton</b> widget')
Make a push button and add tooltip to this button as well.

btn.move(50, 50)
btn.resize(btn.sizeHint())
Adjust the button’s location and size. sizeHint() mehtod helps
adjust the button to appropriate size.

Results
Figure 3-4. Displaying a tooltip.

# 5: Creating a statusbar
The Main window is a typical application window that has menu
bar, toolbar, and status bar. (QMainWindow official document 참
고)

Main window has its own layout for QMenuBar, QToolBar,


QDockWidget, QStatusBar. It also has a layout only for Central
widget at the center in which no other widgets can be placed.
You can make main application window using QMainWindow
class.

First, let’s use QStatusBar to make status bar on main window.


Status bar is a widget placed at the bottom of the application to
present status information of the application. ( QStatusBar official
document )
To display text on the status bar, use showMessage() method. If
you wish to make text disappear, use clearMessage() method or use
showMessage() method to set the time for the text to be displayed.
If you want the message text that is currently being displayed on
the status bar, use currentMessage() method. QStatusBar class
creates messageChanged() signal whenever the message on the
status bar is changed.

Example
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow

class MyApp(QMainWindow):

def __init__(self):
super().__init__()

self.initUI()

def initUI(self):

self.statusBar().showMessage('Ready')

self.setWindowTitle('Statusbar')
self.setGeometry(300, 300, 300, 200)
self.show()

if __name__ == '__main__':

app = QApplication(sys.argv)
ex = MyApp()
sys.exit(app.exec_())
Now a status bar is displayed below the application window.
Description
self.statusBar().showMessage('Ready')
The status bar is created by calling the statusBar() from
QMainWindow class for the first time.
From the next call, restore the status bar object. You can use
showMessage() method to set the message that will be displayed on
the status bar.

Results
Figure 3-5. Creating a statusbar.

# 6: Creating a menubar
GIn GUI application menubar is commonly used. Many commands
are placed on the menu bar. ( QMenuBar official document )
In macOS the menu bar works differently; as seen in the below
example, adding one more line of code
(menubar.setNativeMenuBar(False)) allows the same results to be
yielded in macOS.
First, as shown below, save the icon(exit.png) for the menu in the
folder.

Example
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QAction,
qApp
from PyQt5.QtGui import QIcon

class MyApp(QMainWindow):

def __init__(self):
super().__init__()

self.initUI()

def initUI(self):

exitAction = QAction(QIcon('exit.png'), 'Exit', self)


exitAction.setShortcut('Ctrl+Q')
exitAction.setStatusTip('Exit application')
exitAction.triggered.connect(qApp.quit)
self.statusBar()

menubar = self.menuBar()
menubar.setNativeMenuBar(False)
fileMenu = menubar.addMenu('&File')
fileMenu.addAction(exitAction)

self.setWindowTitle('Menubar')
self.setGeometry(300, 300, 300, 200)
self.show()

if __name__ == '__main__':

app = QApplication(sys.argv)
ex = MyApp()
sys.exit(app.exec_())
We made a menu bar that has one menu. This menu helps quit
application when you click on it. This feature can also be run with
shortcut (Ctrl+Q).

Description
exitAction = QAction(QIcon('exit.png'), 'Exit', self)
exitAction.setShortcut('Ctrl+Q')
exitAction.setStatusTip('Exit application')
With these four lines of codes, make an action that has an
icon(exit.png) and ‘Exit’ label, and define a shortcut for this action.
Also, use setStatusTip() method to set the status tip to be displayed
on the status bar when you put the cursor on the menu.

exitAction.triggered.connect(qApp.quit)
When you select this action, the triggered signal connects to the
quit() method from QApplication widget and quits the application.

menubar = self.menuBar()
menubar.setNativeMenuBar(False)
fileMenu = menubar.addMenu('&File')
fileMenu.addAction(exitAction)
menuBar() method creates a menu bar. Then make ‘File’ menu and
add ‘exitAction’ action to it.
Ampersand(&) of ‘&File’ helps create shortkeys easily. Because
there is an ampersand in front of ‘F’, ‘Alt+F’ becomes the shortkey
for ‘File’ menu. If you put the ampersand in front of ‘i’, then
‘Alt+I’ becomes the shortkey.

Results
Figure 3-6. Creating a menubar.

# 7: Creating a toolbar
While ‘menu’ is a collection of all the commands used in the
application, toolbar makes frequently used commands more
convenient to use. (QToolBar official document 참고 )
Save the icons for the toolbar functions(save.png, edit.png,
print.png, exit.png) in the folder.

Example
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QAction,
qApp
from PyQt5.QtGui import QIcon

class MyApp(QMainWindow):

def __init__(self):
super().__init__()

self.initUI()

def initUI(self):
exitAction = QAction(QIcon('exit.png'), 'Exit', self)
exitAction.setShortcut('Ctrl+Q')
exitAction.setStatusTip('Exit application')
exitAction.triggered.connect(qApp.quit)

self.statusBar()

self.toolbar = self.addToolBar('Exit')
self.toolbar.addAction(exitAction)

self.setWindowTitle('Toolbar')
self.setGeometry(300, 300, 300, 200)
self.show()

if __name__ == '__main__':

app = QApplication(sys.argv)
ex = MyApp()
sys.exit(app.exec_())
Here we made a simple toolbar. The toolbar includes ‘exitAction’
which quits the application when selected.

Description
exitAction = QAction(QIcon('exit.png'), 'Exit', self)
exitAction.setShortcut('Ctrl+Q')
exitAction.setStatusTip('Exit application')
exitAction.triggered.connect(qApp.quit)
Create a QAction object like you did for menu bar. This object
includes icon(exit.png) and label(‘Exit’) and can be run through
shortkey(Ctrl+Q).
Show the message(‘Exit application’) on the status bar, and the
signal created when you click on it is connected to the quit()
method.
self.toolbar = self.addToolBar('Exit')
self.toolbar.addAction(exitAction)
Use addToolbar() to create a toolbar, and use addAction() to add
exitAction to the toolbar.

Results

Figure 3-7. Creating a toolbar.


# 8: Centering window

Let’s place the window in the center of the screen as shown above.

Example
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QDesktopWidget

class MyApp(QWidget):

def __init__(self):
super().__init__()

self.initUI()

def initUI(self):

self.setWindowTitle('Centering')
self.resize(500, 350)
self.center()
self.show()
def center(self):

qr = self.frameGeometry()
cp = QDesktopWidget().availableGeometry().center()
qr.moveCenter(cp)
self.move(qr.topLeft())

if __name__ == '__main__':

app = QApplication(sys.argv)
ex = MyApp()
sys.exit(app.exec_())
The window appears on the center of the screen.

Description
self.center()
Centering the window works through center() method.

qr = self.frameGeometry()
Use frameGeometry() method to get the location and size of the
window.

cp = QDesktopWidget().availableGeometry().center()
Find out the center location for the monitor screen you use.

qr.moveCenter(cp)
Move the rectangular position of the window to the center of the
screen.

self.move(qr.topLeft())
Move the current window to the rectangle(qr) position that you
moved to the center of the screen. As a result the center of the
current window matches the center of the screen and makes the
window appear in the center.

# 9: Displaying date and time


You can use QDate, QTime, QDateTime classes from QtCore
module to display date and time on the application.
For more details, see link below.

QDate official document


QTime official document
QDateTime official document

Displaying date
The QDate class provides date-related features.

Print current date


First let’s use QDate class to print the date.
from PyQt5.QtCore import QDate

now = QDate.currentDate()
print(now.toString())
currentDate() method restores current date.
You can use toString() method to print current date as a string. The
results are as follows.
수 1 2 2019
Set the date format
With the format parameter of toString() method, you can set the
format of the date.
from PyQt5.QtCore import QDate, Qt

now = QDate.currentDate()
print(now.toString('d.M.yy'))
print(now.toString('dd.MM.yyyy'))
print(now.toString('ddd.MMMM.yyyy'))
print(now.toString(Qt.ISODate))
print(now.toString(Qt.DefaultLocaleLongDate))
‘d’ stands for day, ‘M’ for month, ‘y’ for year. The format of the
date varies depending on the number of characters.
By typing Qt.ISODate, Qt.DefaultLocaleLongDate, you can print
to the default settings for the ISO standard format or application.
The results are as follows.
2.1.19
02.01.2019
수 .1 월 .2019
2019-01-02
2019 년 1 월 2 일 수요일

See the table below or refer to the official document for further
details.
Displaying time
You can use QTime class to print current time.

Print current time


from PyQt5.QtCore import QTime

time = QTime.currentTime()
print(time.toString())
currentTime() method restores current time.
toString() method restores current time as a string. The results are
as follows.
15:41:22

Set the time format


from PyQt5.QtCore import QTime, Qt

time = QTime.currentTime()
print(time.toString('h.m.s'))
print(time.toString('hh.mm.ss'))
print(time.toString('hh.mm.ss.zzz'))
print(time.toString(Qt.DefaultLocaleLongDate))
print(time.toString(Qt.DefaultLocaleShortDate))
‘h’ stands for hour, ‘m’ for minute, ‘s’ for seconds, and ‘z’ stands
for 1/1000 seconds.
Just like what we did with date formatting, you can use
Qt.DefaultLocaleLongDate or Qt.DefaultLocaleShortDate to set
the format for time.
The results are as follows.
16.2.3
16.02.03
16.02.03.610
오후 4:02:03
오후 4:02

See the table below or refer to the official document for further
details.
Displaying date and time
You can use QDateTime class to print current date and time
together.

Print current date and time


from PyQt5.QtCore import QDateTime

datetime = QDateTime.currentDateTime()
print(datetime.toString())
currentDateTime() method restores current date and time.
toString() method restores date and time as as string.

Set date and time format


from PyQt5.QtCore import QDateTime, Qt

datetime = QDateTime.currentDateTime()
print(datetime.toString('d.M.yy hh:mm:ss'))
print(datetime.toString('dd.MM.yyyy, hh:mm:ss'))
print(datetime.toString(Qt.DefaultLocaleLongDate))
print(datetime.toString(Qt.DefaultLocaleShortDate))
Like the examples above, you can use ‘d’, ‘M’, ‘y’ for date and ‘h’,
‘m’, ‘s’ for time to set the format in which date and time is
displayed.
Also, you can input Qt.DefaultLocaleLongDate or
Qt.DefaultLocaleShortDate.

Displaying date on statusbar


Let’s print today’s date on the status bar.
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow
from PyQt5.QtCore import QDate, Qt

class MyApp(QMainWindow):

def __init__(self):
super().__init__()

self.date = QDate.currentDate()
self.initUI()

def initUI(self):

self.statusBar().showMessage(self.date.toString(Qt.DefaultLocaleLon
gDate))

self.setWindowTitle('Date')
self.setGeometry(300, 300, 400, 200)
self.show()

if __name__ == '__main__':

app = QApplication(sys.argv)
ex = MyApp()
sys.exit(app.exec_())
Use currentDate() method to get today’s date and use
showMessage() method to display the date on the status bar.

Figure 3-9. Displaying date on statusbar.

# 10: Customizing style


You can freely customize various components of the application
using setStyleSheet().

Example
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QLabel,
QVBoxLayout

class MyApp(QWidget):

def __init__(self):
super().__init__()

self.initUI()

def initUI(self):

lbl_red = QLabel('Red')
lbl_green = QLabel('Green')
lbl_blue = QLabel('Blue')

lbl_red.setStyleSheet("color: red;"
"border-style: solid;"
"border-width: 2px;"
"border-color: #FA8072;"
"border-radius: 3px")
lbl_green.setStyleSheet("color: green;"
"background-color: #7FFFD4")
lbl_blue.setStyleSheet("color: blue;"
"background-color: #87CEFA;"
"border-style: dashed;"
"border-width: 3px;"
"border-color: #1E90FF")

vbox = QVBoxLayout()
vbox.addWidget(lbl_red)
vbox.addWidget(lbl_green)
vbox.addWidget(lbl_blue)

self.setLayout(vbox)

self.setWindowTitle('Stylesheet')
self.setGeometry(300, 300, 300, 200)
self.show()

if __name__ == '__main__':
app = QApplication(sys.argv)
ex = MyApp()
sys.exit(app.exec_())
Customize the three label widgets in various styles.

Description
lbl_red = QLabel('Red')
lbl_green = QLabel('Green')
lbl_blue = QLabel('Blue')
Use QLabel class to make three label widgets. Set the label text as
‘Red’, ‘Green’, ‘Blue’.

lbl_red.setStyleSheet("color: red;"
"border-style: solid;"
"border-width: 2px;"
"border-color: #FA8072;"
"border-radius: 3px")
Use setStyleSheet() method to make the font red, the border line
solid with 2px weights, the border color as #FA8072 and round the
corner as much as 3px.

lbl_green.setStyleSheet("color: green;"
"background-color: #7FFFD4")
Similarly, make the lbl_green label font green and the background
color #7FFFD4.

lbl_blue.setStyleSheet("color: blue;"
"background-color: #87CEFA;"
"border-style: dashed;"
"border-width: 3px;"
"border-color: #1E90FF")
Make lbl_blue label font blue, background color #87CEFA, border
line dashed and weighted 3px, and border color #1E90FF.

vbox = QVBoxLayout()
vbox.addWidget(lbl_red)
vbox.addWidget(lbl_green)
vbox.addWidget(lbl_blue)

self.setLayout(vbox)
Use QVBoxLayout() to position the three label widgets vertically.
For more information about vertical box layout, refer to the box
layout page.
For more styles, refer to Stylesheet reference page .

Results
Figure 3-10. Customizing style.
PART 3: PyQt5 Layout
# 1: Absolute positioning
The absolute positioning method places each widget by setting its
location and size in pixels. When using the absolute layout method,
make sure that you understand the following limitations:

Even if you resize the size of the window, the position


and size of the widget does not change.
The application may look different in various platforms.
Changing the font of an application can damage the
layout.
If you want to change the layout, you have to start from
scratch and this is very bothersome.

We’ll place two labels and two push button widgets with absolute
positioning.

Example
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QLabel,
QPushButton

class MyApp(QWidget):

def __init__(self):
super().__init__()
self.initUI()

def initUI(self):

label1 = QLabel('Label1', self)


label1.move(20, 20)
label2 = QLabel('Label2', self)
label2.move(20, 60)

btn1 = QPushButton('Button1', self)


btn1.move(80, 13)
btn2 = QPushButton('Button2', self)
btn2.move(80, 53)

self.setWindowTitle('Absolute Positioning')
self.setGeometry(300, 300, 400, 200)
self.show()

if __name__ == '__main__':

app = QApplication(sys.argv)
ex = MyApp()
sys.exit(app.exec_())
Use move() method to set the widget’s position. Set the x,y
coordinates of the labels(label1, label2) and push buttons(btn1,
btn2) to adjust the position.
The coordinate system starts at the top left corner. The x
coordinates increases from left to right, and the y coordinates
increases from top to bottom.

Description
label1 = QLabel('Label1', self)
label1.move(20, 20)
Make a label and move it to x=20, y=20.
btn1 = QPushButton('Button1', self)
btn1.move(80, 13)
Make a push button and move it to x=80, y=13.

Results

Figure 4-1. Absolute positioning.


# 2: Box layout
The box layout class provides a much more flexible and practical
layout. ( QBoxLayout official document )
QHBoxLayout and QVBoxLayout are layout classes that sort
multiple widgets horizontally and vertically. The QHBoxLayout
and QVBoxLayout creators create a horizontal and vertical box,
where you can insert other layout boxes or place widgets.
In the example code, use one horizontal and one vertical box to
place two buttons at the bottom center of the widget. Let’s use the
addStretch() method and adjust the ‘stretch factor’ to create the
space you need.

Example
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton,
QHBoxLayout, QVBoxLayout

class MyApp(QWidget):

def __init__(self):
super().__init__()

self.initUI()

def initUI(self):

okButton = QPushButton('OK')
cancelButton = QPushButton('Cancel')

hbox = QHBoxLayout()
hbox.addStretch(1)
hbox.addWidget(okButton)
hbox.addWidget(cancelButton)
hbox.addStretch(1)

vbox = QVBoxLayout()
vbox.addStretch(3)
vbox.addLayout(hbox)
vbox.addStretch(1)

self.setLayout(vbox)

self.setWindowTitle('Box Layout')
self.setGeometry(300, 300, 300, 200)
self.show()

if __name__ == '__main__':

app = QApplication(sys.argv)
ex = MyApp()
sys.exit(app.exec_())
Place the two buttons below the center of the window. The two
buttons will stay at the same position regardless of the size of the
window.

Description
okButton = QPushButton('OK')
cancelButton = QPushButton('Cancel')
We made two buttons.

hbox = QHBoxLayout()
hbox.addStretch(1)
hbox.addWidget(okButton)
hbox.addWidget(cancelButton)
hbox.addStretch(1)
This addStretch() method provides a flexible empty space. Because
the stretch factor on both buttons is equal to 1, the size of these
blank spaces is always the same regardless of the window size.

vbox = QVBoxLayout()
vbox.addStretch(3)
vbox.addLayout(hbox)
vbox.addStretch(1)
Next put the horizontal box(hbox) in the vertical box(vbox). The
stretch factor of the vertical box pushes the horizontal box down so
that the two buttons are located at the bottom of the window.
The size of the blank spaces above and below the horizontal box
will always be 3:1. Changing the stretch factor several times will
help you understand better.

self.setLayout(vbox)
Finally, set the vertical box as the main layout of the window.

Results
Figure 4-2. Box layout.

# 3: Grid layout
The most common layout class is ‘grid layout’. This layout class
separates the space in the widget by row and column.
Use QGridLayout class to create grid layout. ( QGridLayout
official document )

QGridLayout official document

For the example dialog above, it is divided into three rows and five
columns, and the widget is placed at the right place.

Example
import sys
from PyQt5.QtWidgets import (QApplication, QWidget, QGridLayout,
QLabel, QLineEdit, QTextEdit)

class MyApp(QWidget):

def __init__(self):
super().__init__()

self.initUI()

def initUI(self):

grid = QGridLayout()
self.setLayout(grid)

grid.addWidget(QLabel('Title:'), 0, 0)
grid.addWidget(QLabel('Author:'), 1, 0)
grid.addWidget(QLabel('Review:'), 2, 0)

grid.addWidget(QLineEdit(), 0, 1)
grid.addWidget(QLineEdit(), 1, 1)
grid.addWidget(QTextEdit(), 2, 1)

self.setWindowTitle('QGridLayout')
self.setGeometry(300, 300, 300, 200)
self.show()

if __name__ == '__main__':
app = QApplication(sys.argv)
ex = MyApp()
sys.exit(app.exec_())
Three labels, two line editors, and one text editor were placed in
grid form.

Description
grid = QGridLayout()
self.setLayout(grid)
Make QGridLayout and set it as the layout for application window.

grid.addWidget(QLabel('Title:'), 0, 0)
grid.addWidget(QLabel('Author:'), 1, 0)
grid.addWidget(QLabel('Review:'), 2, 0)
Enter the widget you want to add in the first parameter in the
addWidget() method, enter the row and column numbers in the
second and third parameters enter, respectively.
Place the three labels vertically in the first column.

grid.addWidget(QTextEdit(), 2, 1)
Unlike the QLineEdit() widget, QTextEdit() widget is a widget that
can edit many lines of text.

Results

Figure 4-3. Grid layout.


PART 4: PyQt5 Widget

# 1: QPushButton

Push button, or command button, is a button that is used when a


user commands the program to do a certain action, and is the most
common and important widget in GUI programming.
( QPushButton official document )
You can make this with QPushButton class. The methods and
signals often used with the push button are listed in the table below.
Frequently used methods

Method Description
setCheckable() If you set it as True, it distinguishes between the pressed
and unpressed state.
toggle() Changes the state.
setIcon() Sets the icon of the button.
setEnabled() If you set it as False, you cannot use the button.
isChecked() Returns whether a button is selected or not.
setText() Sets the text to be displayed on the button.
text() Returns the text displayed on the button.
Frequently used signals

Signal Description
clicked() Generated when a button is clicked.
pressed() Generated when a button is pressed.
released() Generated when a button is released.
toggled() Generated when the state of the button changes.

Now let’s create a push button using the QPushButton class.

Example
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton,
QVBoxLayout
from PyQt5.QtGui import QIcon, QPixmap

class MyApp(QWidget):

def __init__(self):
super().__init__()

self.initUI()

def initUI(self):

btn1 = QPushButton('&Button1', self)


btn1.setCheckable(True)
btn1.toggle()

btn2 = QPushButton(self)
btn2.setText('Button&2')

btn3 = QPushButton('Button3', self)


btn3.setEnabled(False)
vbox = QVBoxLayout()
vbox.addWidget(btn1)
vbox.addWidget(btn2)
vbox.addWidget(btn3)

self.setLayout(vbox)
self.setWindowTitle('QPushButton')
self.setGeometry(300, 300, 300, 200)
self.show()

if __name__ == '__main__':

app = QApplication(sys.argv)
ex = MyApp()
sys.exit(app.exec_())
Created three different push buttons.

Description
btn1 = QPushButton('&Button1', self)
btn1.setCheckable(True)
btn1.toggle()
Create a push button with PushButton class. The first parameter
specifies the text to appear on the button, and the second parameter
specifies the parent class to which the button belongs.
If you want to specify a shortcut on the button, simply insert the
ampersand (‘&’) in front of the character as shown below. The
shortcut key for this button is ‘Alt+b’.
Setting setCheckable() to True will allow you to remain the
selected or unselected state.
If you call the toggle() method, the state of the button changes.
Therefore, this button is selected when the program starts.
btn2 = QPushButton(self)
btn2.setText('Button&2')
The setText() method also allows you to specify the text to be
displayed on the button. The shortcut key for this button will also
be ‘Alt+2’.
btn3 = QPushButton('Button3', self)
btn3.setEnabled(False)
If setEnabled() is set to False, the button becomes unusable.

Results
Figure 5-1. Make push button.

# 2: QLabel
The QLabel widget is used to create text or image labels. It does
not provide any interaction with the user. ( QLabel official
document )
By default, the label is aligned left in horizontal direction and
center in vertical direction, but it can be adjusted through the
setAlignment() method.
Let’s create a label and try some of the methods related to the
label’s style.

Example
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QLabel,
QVBoxLayout
from PyQt5.QtCore import Qt

class MyApp(QWidget):

def __init__(self):
super().__init__()

self.initUI()

def initUI(self):

label1 = QLabel('First Label', self)


label1.setAlignment(Qt.AlignCenter)

label2 = QLabel('Second Label', self)


label2.setAlignment(Qt.AlignVCenter)

font1 = label1.font()
font1.setPointSize(20)

font2 = label2.font()
font2.setFamily('Times New Roman')
font2.setBold(True)

label1.setFont(font1)
label2.setFont(font2)

layout = QVBoxLayout()
layout.addWidget(label1)
layout.addWidget(label2)

self.setLayout(layout)

self.setWindowTitle('QLabel')
self.setGeometry(300, 300, 300, 200)
self.show()

if __name__ == '__main__':

app = QApplication(sys.argv)
ex = MyApp()
sys.exit(app.exec_())
Two labels were displayed in the vertical box.

Description
label1 = QLabel('First Label', self)
label1.setAlignment(Qt.AlignCenter)
Create a Qlabel widget. Enter the label text and parent widget to
the constructor.
You can adjust the placement of labels with the setAlignment()
method. If you set it with Qt.AlignCenter, it will be aligned in the
center both horizontally and vertically.

font1 = label1.font()
font1.setPointSize(20)
We made a font for the label. Set the font size with the
setPointSize() method.

label2 = QLabel('Second Label', self)


label2.setAlignment(Qt.AlignVCenter)
Create a second label and set it to the center (Qt.AlignVCenter) in
vertical direction only.
To align in center horizontally, enter At.AlignHCenter.

font2 = label2.font()
font2.setFamily('Times New Roman')
font2.setBold(True)
Create a font for the second label and set the font type to Times
New Roman with setFamily() method.
Make the font bold with setBold (true). This time, because the font
size isn’t set, it becomes 13, the default size.

Results
Figure 5-2. Make label.

# 3: QCheckBox
The QCheckBox widget provides buttons with two states: on
(checked)/off (unchecked). This widget provides a check box with
a single text label. ( QCheckBox official document )
When a check box is selected or disabled, a stateChanged() signal
occurs. You can connect this signal to a specific slot when you
want to generate an action whenever the status of the check box
changes.
You can also use the isChecked() method to check if a check box is
selected. The boolean value is restored based on whether or not the
box is selected.

A typical check box only has a select/disable status, but a


setTrustate() method allows it to have a ‘no change’ condition’.
This check box is useful to give users options for choosing or not
choosing.
Use the checkState() method to obtain the status of a check box
with three states. It restores a value of 2/1/0 depending on whether
it’s selected, unchaged or disabled.
The QButtonGroup class allows you to create groups of
exclusive/non-exclusive button groups by tying multiple buttons.
Exclusive button groups can only select one of several buttons.
( QButtonGroup official document )
The following table lists the methods that are frequently used with
the QCheckBox widget.
Frequently used methods

Method Description
text() Return the label text of the check box.
setText() Set the label text for the check box.
isChecked() Return the status of the check box. (True/False)
checkState() Return the status of the check box. (2/1/0)
toggle() Change the status of the check box.
pressed() Create signals when the check box is pressed.
released() Create signals when the check box is released.
clicked() Create signals when the check box is clicked.
stateChanged() Create signals when the state of the check box is changed.

Example
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QCheckBox
from PyQt5.QtCore import Qt

class MyApp(QWidget):

def __init__(self):
super().__init__()

self.initUI()

def initUI(self):

cb = QCheckBox('Show title', self)


cb.move(20, 20)
cb.toggle()
cb.stateChanged.connect(self.changeTitle)
self.setWindowTitle('QCheckBox')
self.setGeometry(300, 300, 300, 200)
self.show()

def changeTitle(self, state):

if state == Qt.Checked:
self.setWindowTitle('QCheckBox')
else:
self.setWindowTitle(' ')

if __name__ == '__main__':

app = QApplication(sys.argv)
ex = MyApp()
sys.exit(app.exec_())
We created a check box, and when it’s checked, the ‘QCheckBox’
text appears in the titlebar. The title appear and disappear according
to the state of the checkbox.

Description
cb = QCheckBox('Show title', self)
Create a check box with a text label called ‘Show Title’.
cb.toggle()
Because the check box appears to be off by default, we used
toggle() method to change it to on.
cb.stateChanged.connect(self.changeTitle)
Connect the signal that occurs when the state of the check box is
changed (stateChanged) to the changeTitle() method.
def changeTitle(self, state):
if state == Qt.Checked:
self.setWindowTitle('QCheckBox')
else:
self.setWindowTitle(' ')
The state of the check box is given as a parameter in the
changeTitle() method. If checked, the title will be represented as
‘QCheckBox’ and if not, as an empty string.

Results
Figure 5-3. Make check box.

# 4: QRadioButton
The QRadioButton widget is used to create buttons that users can
select. This button contains a text label just like the check box.
( QRadioButton official document )
Radio buttons are typically used to make the user select one of
several options. So in a widget many radio buttons are usually set
to autoExclusive . If you select one button, the remaining buttons
are deselected.
Enter False in the setAutoExclusive() method to allow multiple
buttons to be selected at a time. You can also use the
QButtonGroup() method to place multiple groups of exclusive
buttons within a widget. ( QButtonGroup official document )
As with the check box, when the status of the button changes, a
toggled() signal occurs. You can also use the isChecked() method
when you want to get the status of a particular button.

The frequently used methods and signals of QRadioButton are as


follows.

Frequently used methods

Method Description
text() Returns the button’s text.
setText() Sets the text for the label.
setChecked() Sets whether the button is selected or not.
isChecked() Returns whether the button is selected or not.
toggle() Changes the status of the button.

Frequently used signals

메서드 Description
pressed() Generates a signal when a button is pressed.
메서드 Description
released() Generates a signal when a button is released.
clicked() Generated when a button is clicked.
toggled() Generated when the status of the button is changed.

Example
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QRadioButton

class MyApp(QWidget):

def __init__(self):
super().__init__()

self.initUI()

def initUI(self):

rbtn1 = QRadioButton('First Button', self)


rbtn1.move(50, 50)
rbtn1.setChecked(True)

rbtn2 = QRadioButton(self)
rbtn2.move(50, 70)
rbtn2.setText('Second Button')

self.setGeometry(300, 300, 300, 200)


self.setWindowTitle('QRadioButton')
self.show()

if __name__ == '__main__':

app = QApplication(sys.argv)
ex = MyApp()
sys.exit(app.exec_())
We made two radio buttons.

Description
rbtn1 = QRadioButton('First Button', self)
Use QRadioButton to create a radio button. Enter the text to be
included in the label and the parent widget.
rbtn1.setChecked(True)
If setChecked() is set to True, the button is selected and displayed
when the program is running.
rbtn2.setText('Second Button')
setTextYou can also set the text of a label through the setText()
method.

Results
Figure 5-4. Make radio button.

# 5: QComboBox
QComboBox is a widget that takes up a small amount of space,
offers multiple options, and allows you to choose one of them.
( QComboBox official document )

Example
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QLabel,
QComboBox

class MyApp(QWidget):

def __init__(self):
super().__init__()

self.initUI()

def initUI(self):

self.lbl = QLabel('Option1', self)


self.lbl.move(50, 150)

cb = QComboBox(self)
cb.addItem('Option1')
cb.addItem('Option2')
cb.addItem('Option3')
cb.addItem('Option4')
cb.move(50, 50)
cb.activated[str].connect(self.onActivated)

self.setWindowTitle('QComboBox')
self.setGeometry(300, 300, 300, 200)
self.show()

def onActivated(self, text):

self.lbl.setText(text)
self.lbl.adjustSize()

if __name__ == '__main__':

app = QApplication(sys.argv)
ex = MyApp()
sys.exit(app.exec_())
We created a label and a combobox widget, so that the selected
item in the combobox appears on the label.

Description
cb = QComboBox(self)
cb.addItem('Option1')
cb.addItem('Option2')
cb.addItem('Option3')
cb.addItem('Option4')
cb.move(50, 50)
We created a QComboBox widget and added four optional options
using the addItem() method.

cb.activated[str].connect(self.onActivated)
When the option is selected, the onActivated() method is called.

def onActivated(self, text):


self.lbl.setText(text)
self.lbl.adjustSize()
The text of the selected item appears on the label, and with the
adjustSize() method the label’s size is automatically adjusted.

Results
Figure 5-5. Make Combobox.

# 6: QLineEdit

QLineEdit is a widget that lets you enter and modify a single line
of string. ( QLineEdit official document )
By setting echoMode(), it can be used as a ‘write-only’ area. This
feature is useful when receiving inputs such as passwords.
You can set these modes with the setEchoMode() method, and the
inputs and functions are shown in the table below.
Normal mode is the most commonly used and is also the default
setting (e.g. setEchoMode (QLineEdit.Normal) or setEchoMode
(0)).

Constant Value Description


QLineEdit.Normal 0 Display characters as they are
entered. This is the default.
QLineEdit.NoEcho 1 Do not display anything. This may
be appropriate for passwords where
even the length of the password
should be kept secret.
QLineEdit.Password 2 Display platform-dependent
password mask characters instead
of the characters actually entered.
QLineEdit.PasswordEchoOnEdit 3 Display characters as they are
entered while editing otherwise
display characters as with
Password.
You can limit the length of text entered with maxLength() method
or you limit the type of text entered with setValidator() method.
You can edit text with setText() or insert() method, and import
entered text with text() method. If the text entered by echoMode
differs from the text displayed, you can also import the text
displayed with the displayText() method.
You can select text with setSelection(), selectAll() methods, or
perform actions such as cutting, copying, and pasting with cut(),
copy(), paste() methods. You can also set the alignment of text with
the setAlignment() method.
You can select text with setSelection(), selectAll() methods, or
perform actions such as cutting, copying, and pasting with cut(),
copy(), paste() methods. You can also set the alignment of text with
the setAlignment() method.
Commonly used signals are shown below.
Signal Description
cursorPositionChanged() Generates a signal that occurs when the cursor
moves.
editingFinished() Generates a signal when the editing is finished
(when the Return/Enter button is pressed).
returnPressed() Generates a signal when the Return/Enter button
is pressed.
selectionChanged() Generates a signal when the selected area is
changed.
textChanged() Generates a signal when the text is changed.
textEdited() Generates a signal when the text is edited.

Example
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QLabel,
QLineEdit
class MyApp(QWidget):

def __init__(self):
super().__init__()

self.initUI()

def initUI(self):

self.lbl = QLabel(self)
self.lbl.move(60, 40)

qle = QLineEdit(self)
qle.move(60, 100)
qle.textChanged[str].connect(self.onChanged)

self.setWindowTitle('QLineEdit')
self.setGeometry(300, 300, 300, 200)
self.show()

def onChanged(self, text):

self.lbl.setText(text)
self.lbl.adjustSize()

if __name__ == '__main__':

app = QApplication(sys.argv)
ex = MyApp()
sys.exit(app.exec_())
The widget contains a label and a QLineEdit widget. The label
immediately displays the text that is entered and modified in the
QLineEdit widget.
Description
qle = QLineEdit(self)
We made the QLineEdit widget.

qle.textChanged[str].connect(self.onChanged)
When the text of qle changes, the onChanged() method is called.

def onChanged(self, text):

self.lbl.setText(text)
self.lbl.adjustSize()
Within the onChanged() method, let the entered ‘text’ be set as the
text in the label widget (lbl).
Also, use the adjustSize() method to adjust the length of the label
according to the length of the text.

Results
Figure 5-6. Make line editor.

# 7: QLineEdit (Advanced)
When you use the Line Editor, you can apply different settings.
Let’s use the combobox to create a line editor that applies the
settings related to echo mode, validation, alignment, input mask,
read-only.

Example
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *

class MyApp(QWidget):

def __init__(self):
super().__init__()

self.initUI()

def initUI(self):

# echo_group
self.echo_group = QGroupBox('Echo')
self.echo_label = QLabel('Mode:')

self.echo_cb = QComboBox()
self.echo_cb.addItem('Normal')
self.echo_cb.addItem('No Echo')
self.echo_cb.addItem('Password')
self.echo_cb.addItem('PasswordEchoOnEdit')

self.echo_le = QLineEdit()
self.echo_le.setPlaceholderText('Placeholder Text')
self.echo_le.setFocus()

# validator_group
self.validator_group = QGroupBox('Validator')
self.validator_label = QLabel('Type:')
self.validator_cb = QComboBox()
self.validator_cb.addItem('No validator')
self.validator_cb.addItem('Integer validator')
self.validator_cb.addItem('Double validator')

self.validator_le = QLineEdit()
self.validator_le.setPlaceholderText('Placeholder Text')

# alignment_group
self.alignment_group = QGroupBox('Alignment')
self.alignment_label = QLabel('Type:')

self.alignment_cb = QComboBox()
self.alignment_cb.addItem('Left')
self.alignment_cb.addItem('Centered')
self.alignment_cb.addItem('Right')

self.alignment_le = QLineEdit()
self.alignment_le.setPlaceholderText('Placeholder Text')

# input_mask_group
self.input_mask_group = QGroupBox('Input mask')
self.input_mask_label = QLabel('Type:')

self.input_mask_cb = QComboBox()
self.input_mask_cb.addItem('No mask')
self.input_mask_cb.addItem('Phone number')
self.input_mask_cb.addItem('ISO date')
self.input_mask_cb.addItem('License key')

self.input_mask_le = QLineEdit()
self.input_mask_le.setPlaceholderText('Placeholder Text')

# access_group
self.access_group = QGroupBox('Access')
self.access_label = QLabel('Type:')
self.access_cb = QComboBox()
self.access_cb.addItem('False')
self.access_cb.addItem('True')

self.access_le = QLineEdit()
self.access_le.setPlaceholderText('Placeholder Text')

# activated.connect
self.echo_cb.activated.connect(self.echo_changed)
self.validator_cb.activated.connect(self.validator_changed)
self.alignment_cb.activated.connect(self.alignment_changed)
self.input_mask_cb.activated.connect(self.input_mask_changed)
self.access_cb.activated.connect(self.access_changed)

# echo_layout
self.echo_layout = QGridLayout()
self.echo_layout.addWidget(self.echo_label, 0, 0)
self.echo_layout.addWidget(self.echo_cb, 0, 1)
self.echo_layout.addWidget(self.echo_le, 1, 0, 1, 2)
self.echo_group.setLayout(self.echo_layout)

# validator_layout
self.validator_layout = QGridLayout()
self.validator_layout.addWidget(self.validator_label, 0, 0)
self.validator_layout.addWidget(self.validator_cb, 0, 1)
self.validator_layout.addWidget(self.validator_le, 1, 0, 1, 2)
self.validator_group.setLayout(self.validator_layout)

# alignment_layout
self.alignment_layout = QGridLayout()
self.alignment_layout.addWidget(self.alignment_label, 0, 0)
self.alignment_layout.addWidget(self.alignment_cb, 0, 1)
self.alignment_layout.addWidget(self.alignment_le, 1, 0, 1, 2)
self.alignment_group.setLayout(self.alignment_layout)

# input_mask_layout
self.input_mask_layout = QGridLayout()
self.input_mask_layout.addWidget(self.input_mask_label, 0, 0)
self.input_mask_layout.addWidget(self.input_mask_cb, 0, 1)
self.input_mask_layout.addWidget(self.input_mask_le, 1, 0, 1, 2)
self.input_mask_group.setLayout(self.input_mask_layout)

# access_layout
self.access_layout = QGridLayout()
self.access_layout.addWidget(self.access_label, 0, 0)
self.access_layout.addWidget(self.access_cb, 0, 1)
self.access_layout.addWidget(self.access_le, 1, 0, 1, 2)
self.access_group.setLayout(self.access_layout)

# layout
self.layout = QGridLayout()
self.layout.addWidget(self.echo_group, 0, 0)
self.layout.addWidget(self.validator_group, 1, 0)
self.layout.addWidget(self.alignment_group, 2, 0)
self.layout.addWidget(self.input_mask_group,0, 1)
self.layout.addWidget(self.access_group, 1, 1)

self.setLayout(self.layout)

self.setWindowTitle('Line Editor')
self.show()

def echo_changed(self, index):

if index == 0:
self.echo_le.setEchoMode(QLineEdit.Normal)
elif index == 1:
self.echo_le.setEchoMode(QLineEdit.NoEcho)
elif index == 2:
self.echo_le.setEchoMode(QLineEdit.Password)
elif index == 3:
self.echo_le.setEchoMode(QLineEdit.PasswordEchoOnEdit)

def validator_changed(self, index):


if index == 0:
self.validator_le.setValidator(None)
elif index == 1:
self.validator_le.setValidator(QIntValidator(-99, 99))
elif index == 2:
double_validator = QDoubleValidator(-999.0, 999.0, 2)
double_validator.setNotation(QDoubleValidator.StandardNotation)
self.validator_le.setValidator(double_validator)

self.validator_le.clear()

def alignment_changed(self, index):

if index == 0:
self.alignment_le.setAlignment(Qt.AlignLeft)
elif index == 1:
self.alignment_le.setAlignment(Qt.AlignCenter)
elif index == 2:
self.alignment_le.setAlignment(Qt.AlignRight)

def input_mask_changed(self, index):

if index == 0:
self.input_mask_le.setInputMask('')
elif index == 1:
self.input_mask_le.setInputMask('000-0000-0000')
elif index == 2:
self.input_mask_le.setInputMask('0000-00-00')
self.input_mask_le.setText('20190410')
self.input_mask_le.setCursorPosition(0)
elif index == 3:
self.input_mask_le.setInputMask('>AAAAA-AAAAA-AAAAA-
AAAAA;#')

def access_changed(self, index):


if index == 0:
self.access_le.setReadOnly(False)
elif index == 1:
self.access_le.setReadOnly(True)

if __name__ == '__main__':

app = QApplication(sys.argv)
ex = MyApp()
sys.exit(app.exec_())
The widget contains one label and one QLineEdit widget. The label
immediately displays the text that is entered and modified in the
QLineEdit widget.

Description
# echo_group
self.echo_group = QGroupBox('Echo')
self.echo_label = QLabel('Mode:')

self.echo_cb = QComboBox()
self.echo_cb.addItem('Normal')
self.echo_cb.addItem('No Echo')
self.echo_cb.addItem('Password')
self.echo_cb.addItem('PasswordEchoOnEdit')

self.echo_le = QLineEdit()
self.echo_le.setPlaceholderText('Placeholder Text')
self.echo_le.setFocus()
Create a group box (echo_group) to contain widgets related to echo
mode.
Create a label, a combobox, and a line-editor. Add items related to
echo mode to the combo box.
For example, if you select ‘Password’, the text in the line editor is
displayed in password mode.
Make the other four group boxes in a similar fashion.

# activated.connect
self.echo_cb.activated.connect(self.echo_changed)
self.validator_cb.activated.connect(self.validator_changed)
self.alignment_cb.activated.connect(self.alignment_changed)
self.input_mask_cb.activated.connect(self.input_mask_changed)
self.access_cb.activated.connect(self.access_changed)
Connect the signal that is released when each combo box is
selected (activated) to each method.

# echo_layout
self.echo_layout = QGridLayout()
self.echo_layout.addWidget(self.echo_label, 0, 0)
self.echo_layout.addWidget(self.echo_cb, 0, 1)
self.echo_layout.addWidget(self.echo_le, 1, 0, 1, 2)
self.echo_group.setLayout(self.echo_layout)
Use the grid layout to place labels, comboboxes, and line editors,
and set them as the layout of the Group Box.

# layout
self.layout = QGridLayout()
self.layout.addWidget(self.echo_group, 0, 0)
self.layout.addWidget(self.validator_group, 1, 0)
self.layout.addWidget(self.alignment_group, 2, 0)
self.layout.addWidget(self.input_mask_group,0, 1)
self.layout.addWidget(self.access_group, 1, 1)

self.setLayout(self.layout)
Use the grid layout to place five group boxes.

def echo_changed(self, index):


if index == 0:
self.echo_le.setEchoMode(QLineEdit.Normal)
elif index == 1:
self.echo_le.setEchoMode(QLineEdit.NoEcho)
elif index == 2:
self.echo_le.setEchoMode(QLineEdit.Password)
elif index == 3:
self.echo_le.setEchoMode(QLineEdit.PasswordEchoOnEdit)
The echo_changed method is executed when Echo Combo Box
(echo_cb) is selected.
If you select the first item (‘Normal’), use setEchoMode() to set the
line editor to Normal mode. If you select the third item
(‘Password’), it will be in password mode.

Results
Figure 5-6. Make line editor (Advanced).

# 8: QProgressBar

The figure above shows the basic progress bar for macOS (top) and
Windows 7 (bottom). The progress bar is a widget that is used for
time-consuming tasks. ( QProgressBar official document )
The QProgressBar widget provides a horizontal and vertical
progress bar. You can set the minimum and maximum values for
the progress bar with setMinimum() and setMaximum() methods,
or you can set the range at once with setRange() methods. Defaults
are 0 and 99.
The setValue() method lets you set the progress of the progress bar
to a specific value, and the reset() method returns to its initial state.

If you set both the minimum and maximum values for the progress
bar to 0, the progress bar will always be displayed as in progress as
shown in the figure above. This feature can be useful if you don’t
know the capacity of the file you’re downloading.

Example
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton,
QProgressBar
from PyQt5.QtCore import QBasicTimer

class MyApp(QWidget):

def __init__(self):
super().__init__()

self.initUI()

def initUI(self):

self.pbar = QProgressBar(self)
self.pbar.setGeometry(30, 40, 200, 25)

self.btn = QPushButton('Start', self)


self.btn.move(40, 80)
self.btn.clicked.connect(self.doAction)

self.timer = QBasicTimer()
self.step = 0

self.setWindowTitle('QProgressBar')
self.setGeometry(300, 300, 300, 200)
self.show()

def timerEvent(self, e):

if self.step >= 100:

self.timer.stop()
self.btn.setText('Finished')
return

self.step = self.step + 1
self.pbar.setValue(self.step)

def doAction(self):

if self.timer.isActive():
self.timer.stop()
self.btn.setText('Start')
else:
self.timer.start(100, self)
self.btn.setText('Stop')

if __name__ == '__main__':

app = QApplication(sys.argv)
ex = MyApp()
sys.exit(app.exec_())
Create a horizontal progress bar and pushbutton. The pushbutton
lets you start and stop the progress bar.

Description
self.pbar = QProgressBar(self)
Create a single progress bar with the QProgressBar generator.

self.timer = QBasicTimer()
To activate the progress bar, use a timer object.

self.timer.start(100, self)
To run a timer event, call the start() method This method has two
parameters: the first is the end time and the second is the object on
which the event will be performed.

def timerEvent(self, e):

if self.step >= 100:

self.timer.stop()
self.btn.setText('Finished')
return

self.step = self.step + 1
self.pbar.setValue(self.step)
Each QObject and its descendants has a timerEvent() event handler.
To respond to a timer event, reconfigure the event handler.

def doAction(self):

if self.timer.isActive():
self.timer.stop()
self.btn.setText('Start')
else:
self.timer.start(100, self)
self.btn.setText('Stop')
The doAction() method helps start and stop the timer.

Results

Figure 5-8. Make progress bar.


# 9: QSlider & QDial

The QSlider provides a slider in horizontal or vertical direction.


The slider is a widget that adjusts value within a limited range.
( QSlider official document )

Use the setTickInterval() method to adjust the interval of the


slider’s tick, and use the setTickPosition() method to adjust the
position of the tick in the slider.
The input value of the setTickInterval() method stands for value,
not pixel.
The input values and functions of the setTickPosition() method are
shown in the table below. (e.g.: setTickPosition(QSlider.NoTicks)
or setTickPosition(0))

Constant Value Description


QSlider.NoTicks 0 Do not show ticks.
QSlider.TicksAbove 1 Display the tick on top of the
(horizontal) slider.
QSlider.TicksBelow 2 Display the tick on the bottom of the
(horizontal) slider.
QSlider.TicksBothSides 3 Display the tick on both sides of the
(horizontal) slider.
QSlider.TicksLeft TicksAbove Display the tick on the left of the
(vertical) slider.
QSlider.TicksRight TicksBelow Display the tick on the right of the
(vertical) slider.
QDial is a dial widget that represents the slider in a circular form
and shares the same signals, slots, and methods. ( QDial official
document )

Use the setNotchesVisible() method to display notch in the Dial


widget as shown above. When set to True, the notches are
displayed along the round dial. By default, the notch is disabled.
The most frequently used signals in the QSlider and QDial widgets
are shown below. In the example, we will use the valueChanged
signal.

Value Description
valueChanged() Emitted when the slider’s value has changed. The
tracking() determines whether this signal is emitted during
user interaction.
sliderPressed() Emitted when the user starts to drag the slider.
sliderMoved() Emitted when the user drags the slider.
sliderReleased() Emitted when the user releases the slider.
Example
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QSlider, QDial,
QPushButton
from PyQt5.QtCore import Qt

class MyApp(QWidget):

def __init__(self):
super().__init__()

self.initUI()

def initUI(self):

self.slider = QSlider(Qt.Horizontal, self)


self.slider.move(30, 30)
self.slider.setRange(0, 50)
self.slider.setSingleStep(2)

self.dial = QDial(self)
self.dial.move(30, 50)
self.dial.setRange(0, 50)

btn = QPushButton('Default', self)


btn.move(35, 160)

self.slider.valueChanged.connect(self.dial.setValue)
self.dial.valueChanged.connect(self.slider.setValue)
btn.clicked.connect(self.button_clicked)

self.setWindowTitle('QSlider and QDial')


self.setGeometry(300, 300, 400, 200)
self.show()
def button_clicked(self):
self.slider.setValue(0)
self.dial.setValue(0)

if __name__ == '__main__':

app = QApplication(sys.argv)
ex = MyApp()
sys.exit(app.exec_())
We made a slider, dial widget, and a push button. The slider and
dial are linked together so that they always have the same value,
and when you press the push button, both widgets’ values become
0.

Description
self.slider = QSlider(Qt.Horizontal, self)
We created a QSlider widget. Enter Qt.Horizontal or Qt.Enter
Vertical to set the horizontal or vertical orientation.

self.slider.setRange(0, 50)
self.slider.setSingleStep(2)
setRange() method sets the range of the value from 0 to 50. The
setSingleStep() method sets the minimum adjustable units.

self.dial = QDial(self)
We made a QDial widget.

self.dial.setRange(0, 50)
Just like the slider, setRange() sets the range.

self.slider.valueChanged.connect(self.dial.setValue)
self.dial.valueChanged.connect(self.slider.setValue)
The values of the two widgets are always identical by connecting
the signals that occur when the values of the slider and dial change
to each other’s dial and slider value adjusting method (setValue).
btn.clicked.connect(self.button_clicked)
Connect the signal that occurs when you click the ‘Default’ push
button to the button_clicked method.
def button_clicked(self):
self.slider.setValue(0)
self.dial.setValue(0)
The button_clicked() method adjusts both the slider and dial values
to zero. Therefore, when the ‘Default’ pushbutton is clicked, the
values on the slider and dial are reset to 0.

Results
Figure 5-9. Make slider and dial widgets.

# 10: QSplitter
QSplitter class implements the splitter widget. Splitter allows you
to resize child widgets’ size by dragging the boundaries.
Let’s split the widget into four smaller areas through an example.

Example
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QHBoxLayout,
QFrame, QSplitter
from PyQt5.QtCore import Qt

class MyApp(QWidget):

def __init__(self):
super().__init__()

self.initUI()

def initUI(self):
hbox = QHBoxLayout()

top = QFrame()
top.setFrameShape(QFrame.Box)

midleft = QFrame()
midleft.setFrameShape(QFrame.StyledPanel)

midright = QFrame()
midright.setFrameShape(QFrame.Panel)

bottom = QFrame()
bottom.setFrameShape(QFrame.WinPanel)
bottom.setFrameShadow(QFrame.Sunken)

splitter1 = QSplitter(Qt.Horizontal)
splitter1.addWidget(midleft)
splitter1.addWidget(midright)

splitter2 = QSplitter(Qt.Vertical)
splitter2.addWidget(top)
splitter2.addWidget(splitter1)
splitter2.addWidget(bottom)

hbox.addWidget(splitter2)
self.setLayout(hbox)

self.setGeometry(300, 300, 300, 200)


self.setWindowTitle('QSplitter')
self.show()

if __name__ == '__main__':

app = QApplication(sys.argv)
ex = MyApp()
sys.exit(app.exec_())
The window is divided into four small areas. You can set different
styles for the frames of each area.

Description
top = QFrame()
top.setFrameShape(QFrame.Box)

midleft = QFrame()
midleft.setFrameShape(QFrame.StyledPanel)

midright = QFrame()
midright.setFrameShape(QFrame.Panel)

bottom = QFrame()
bottom.setFrameShape(QFrame.WinPanel)
bottom.setFrameShadow(QFrame.Sunken)
Create frames for each area. You can set the shape of the frame and
style of the shadow using setFrameShape and setFrameShadow.
As shown in the example, you can use
NoFrame/Box/Panel/ScheduledPanel/HLine/VLine/WinPanel for
setFrameShadow, and the Plain/Raised/Sunken constant for
setFrameShadow.
Refer to the image below for descriptions and results of each
constant’s use.

Constant that sets the shape of a frame


Constant that sets the shadow of a frame

The shape of the frame and shadow


splitter1 = QSplitter(Qt.Horizontal)
splitter1.addWidget(midleft)
splitter1.addWidget(midright)

splitter2 = QSplitter(Qt.Vertical)
splitter2.addWidget(top)
splitter2.addWidget(splitter1)
splitter2.addWidget(bottom)
Use the QSplitter to split horizontally, and insert the midleft frame
widget on the left and the midright frame widget on the right.
Next, break it vertically and insert three frame widgets: top,
splitter1, and bottom.
hbox.addWidget(splitter2)
self.setLayout(hbox)
Place the splitter2 widget in the horizontal box layout and set it as
the overall layout.

Results

Figure 5-10. Make Splitter widget.

# 11: QGroupBox
As shown above, the QGroupBox widget provides a group box
frame with a title.

Example
import sys
from PyQt5.QtWidgets import (QApplication, QWidget, QGroupBox,
QRadioButton, QCheckBox, QPushButton, QMenu, QGridLayout,
QVBoxLayout)

class MyApp(QWidget):

def __init__(self):
super().__init__()

self.initUI()

def initUI(self):

grid = QGridLayout()
grid.addWidget(self.createFirstExclusiveGroup(), 0, 0)
grid.addWidget(self.createSecondExclusiveGroup(), 1, 0)
grid.addWidget(self.createNonExclusiveGroup(), 0, 1)
grid.addWidget(self.createPushButtonGroup(), 1, 1)

self.setLayout(grid)

self.setWindowTitle('Box Layout')
self.setGeometry(300, 300, 480, 320)
self.show()

def createFirstExclusiveGroup(self):
groupbox = QGroupBox('Exclusive Radio Buttons')

radio1 = QRadioButton('Radio1')
radio2 = QRadioButton('Radio2')
radio3 = QRadioButton('Radio3')
radio1.setChecked(True)

vbox = QVBoxLayout()
vbox.addWidget(radio1)
vbox.addWidget(radio2)
vbox.addWidget(radio3)
groupbox.setLayout(vbox)

return groupbox

def createSecondExclusiveGroup(self):
groupbox = QGroupBox('Exclusive Radio Buttons')
groupbox.setCheckable(True)
groupbox.setChecked(False)

radio1 = QRadioButton('Radio1')
radio2 = QRadioButton('Radio2')
radio3 = QRadioButton('Radio3')
radio1.setChecked(True)
checkbox = QCheckBox('Independent Checkbox')
checkbox.setChecked(True)

vbox = QVBoxLayout()
vbox.addWidget(radio1)
vbox.addWidget(radio2)
vbox.addWidget(radio3)
vbox.addWidget(checkbox)
vbox.addStretch(1)
groupbox.setLayout(vbox)

return groupbox

def createNonExclusiveGroup(self):
groupbox = QGroupBox('Non-Exclusive Checkboxes')
groupbox.setFlat(True)

checkbox1 = QCheckBox('Checkbox1')
checkbox2 = QCheckBox('Checkbox2')
checkbox2.setChecked(True)
tristatebox = QCheckBox('Tri-state Button')
tristatebox.setTristate(True)

vbox = QVBoxLayout()
vbox.addWidget(checkbox1)
vbox.addWidget(checkbox2)
vbox.addWidget(tristatebox)
vbox.addStretch(1)
groupbox.setLayout(vbox)

return groupbox

def createPushButtonGroup(self):
groupbox = QGroupBox('Push Buttons')
groupbox.setCheckable(True)
groupbox.setChecked(True)

pushbutton = QPushButton('Normal Button')


togglebutton = QPushButton('Toggle Button')
togglebutton.setCheckable(True)
togglebutton.setChecked(True)
flatbutton = QPushButton('Flat Button')
flatbutton.setFlat(True)
popupbutton = QPushButton('Popup Button')
menu = QMenu(self)
menu.addAction('First Item')
menu.addAction('Second Item')
menu.addAction('Third Item')
menu.addAction('Fourth Item')
popupbutton.setMenu(menu)

vbox = QVBoxLayout()
vbox.addWidget(pushbutton)
vbox.addWidget(togglebutton)
vbox.addWidget(flatbutton)
vbox.addWidget(popupbutton)
vbox.addStretch(1)
groupbox.setLayout(vbox)

return groupbox

if __name__ == '__main__':

app = QApplication(sys.argv)
ex = MyApp()
sys.exit(app.exec_())
We made four group boxes according to the type of button.

Description
grid = QGridLayout()
grid.addWidget(self.createFirstExclusiveGroup(), 0, 0)
grid.addWidget(self.createSecondExclusiveGroup(), 1, 0)
grid.addWidget(self.createNonExclusiveGroup(), 0, 1)
grid.addWidget(self.createPushButtonGroup(), 1, 1)

self.setLayout(grid)
Use the grid layout to place the group boxes.
Group boxes created through each method are placed in each
position via addWidget().

def createFirstExclusiveGroup(self):
groupbox = QGroupBox('Exclusive Radio Buttons')

radio1 = QRadioButton('Radio1')
radio2 = QRadioButton('Radio2')
radio3 = QRadioButton('Radio3')
radio1.setChecked(True)

vbox = QVBoxLayout()
vbox.addWidget(radio1)
vbox.addWidget(radio2)
vbox.addWidget(radio3)
groupbox.setLayout(vbox)

return groupbox
createFirstExclusiveGroup() method creates a group box with
exclusive radio buttons.
The method first creates a groupbox and a button, and then places it
through the vertical box layout.
Finally, set the vertical box layout(vbox) as the layout of the group
box.
We made three radio buttons and placed them vertically.

def createSecondExclusiveGroup(self):
groupbox = QGroupBox('Exclusive Radio Buttons')
groupbox.setCheckable(True)
groupbox.setChecked(False)
createSecondExclusiveGroup() method creates a group box with
three radio buttons and one check box.
You can also make groupbox selectable by using the
setCheckable() method.

def createNonExclusiveGroup(self):
groupbox = QGroupBox('Non-Exclusive Checkboxes')
groupbox.setFlat(True)
Create NonExclusiveGroup() method creates a group box with
non-exclusive check boxes.
Use setFlat() to make the group box look flat.

def createPushButtonGroup(self):
groupbox = QGroupBox('Push Buttons')
groupbox.setCheckable(True)
groupbox.setChecked(True)
createPushButtonGroup() method creates a group box with
multiple push buttons.
Use setCheckable() and setChecked() to make the group box
selectable and selected when run.

Results
Figure 5-10. Make Groupbox widget.

# 12: QTabWidget
While using GUI program, you may find a window with a tab as
shown in the picture above. These tabs can be useful because the
components in the program do not occupy a large area and can be
classified into categories.
We’ll create a widget with two tabs in this example.

Example
import sys
from PyQt5.QtWidgets import (QApplication, QWidget, QTabWidget,
QVBoxLayout)

class MyApp(QWidget):

def __init__(self):
super().__init__()

self.initUI()
def initUI(self):

tab1 = QWidget()
tab2 = QWidget()

tabs = QTabWidget()
tabs.addTab(tab1, 'Tab1')
tabs.addTab(tab2, 'Tab2')

vbox = QVBoxLayout()
vbox.addWidget(tabs)

self.setLayout(vbox)

self.setWindowTitle('QTabWidget')
self.setGeometry(300, 300, 300, 200)
self.show()

if __name__ == '__main__':

app = QApplication(sys.argv)
ex = MyApp()
sys.exit(app.exec_())
A small widget with two tabs is created.

Description
tab1 = QWidget()
tab2 = QWidget()
We created two widgets to be located on each tab.

tabs = QTabWidget()
tabs.addTab(tab1, 'Tab1')
tabs.addTab(tab2, 'Tab2')
Use QTabWidget() to create tabs and use addTab() to add Tab1 and
Tab2 to the tabs.

vbox = QVBoxLayout()
vbox.addWidget(tabs)

self.setLayout(vbox)
Create a vertical box layout and insert a tab widget. Then set the
vertical box as the layout of the widget.

Results
Figure 5-11. Use tab widget to make tabs.

# 13: QTabWidget (Advanced)


Let’s use the tab widget to configure a dialog box that allows you
to receive multiple inputs in different ways.

Example
import sys
from PyQt5.QtWidgets import *

class MyApp(QDialog):

def __init__(self):
super().__init__()

self.initUI()

def initUI(self):

tabs = QTabWidget()
tabs.addTab(FirstTab(), 'First')
tabs.addTab(SecondTab(), 'Second')
tabs.addTab(ThirdTab(), 'Third')

buttonbox = QDialogButtonBox(QDialogButtonBox.Ok |
QDialogButtonBox.Cancel)
buttonbox.accepted.connect(self.accept)
buttonbox.rejected.connect(self.reject)

vbox = QVBoxLayout()
vbox.addWidget(tabs)
vbox.addWidget(buttonbox)

self.setLayout(vbox)

self.setWindowTitle('QTabWidget')
self.setGeometry(300, 300, 400, 300)
self.show()

class FirstTab(QWidget):

def __init__(self):
super().__init__()

self.initUI()

def initUI(self):

name = QLabel('Name:')
nameedit = QLineEdit()
age = QLabel('Age:')
ageedit = QLineEdit()
nation = QLabel('Nation:')
nationedit = QLineEdit()

vbox = QVBoxLayout()
vbox.addWidget(name)
vbox.addWidget(nameedit)
vbox.addWidget(age)
vbox.addWidget(ageedit)
vbox.addWidget(nation)
vbox.addWidget(nationedit)
vbox.addStretch()

self.setLayout(vbox)

class SecondTab(QWidget):

def __init__(self):
super().__init__()

self.initUI()

def initUI(self):

lan_group = QGroupBox('Select Your Language')


combo = QComboBox()
list = ['Korean', 'English', 'Chinese']
combo.addItems(list)

vbox1 = QVBoxLayout()
vbox1.addWidget(combo)
lan_group.setLayout(vbox1)

learn_group = QGroupBox('Select What You Want To Learn')


korean = QCheckBox('Korean')
english = QCheckBox('English')
chinese = QCheckBox('Chinese')

vbox2 = QVBoxLayout()
vbox2.addWidget(korean)
vbox2.addWidget(english)
vbox2.addWidget(chinese)
learn_group.setLayout(vbox2)
vbox = QVBoxLayout()
vbox.addWidget(lan_group)
vbox.addWidget(learn_group)
self.setLayout(vbox)

class ThirdTab(QWidget):

def __init__(self):
super().__init__()

self.initUI()

def initUI(self):

lbl = QLabel('Terms and Conditions')


text_browser = QTextBrowser()
text_browser.setText('This is the terms and conditions')
checkbox = QCheckBox('Check the terms and conditions.')

vbox = QVBoxLayout()
vbox.addWidget(lbl)
vbox.addWidget(text_browser)
vbox.addWidget(checkbox)

self.setLayout(vbox)

if __name__ == '__main__':

app = QApplication(sys.argv)
ex = MyApp()
sys.exit(app.exec_())
A dialog with three tabs is made.
Description
tabs = QTabWidget()
tabs.addTab(FirstTab(), 'First')
tabs.addTab(SecondTab(), 'Second')
tabs.addTab(ThirdTab(), 'Third')

buttonbox = QDialogButtonBox(QDialogButtonBox.Ok |
QDialogButtonBox.Cancel)
buttonbox.accepted.connect(self.accept)
buttonbox.rejected.connect(self.reject)
Create tabs using QTabWidget() and use addTab() to add three tabs.
Use QDialogButtonBox() to create a button box with the ‘OK’ and
‘Cancel’ buttons.

class FirstTab(QWidget):

def __init__(self):
super().__init__()

self.initUI()

def initUI(self):

name = QLabel('Name:')
nameedit = QLineEdit()
age = QLabel('Age:')
ageedit = QLineEdit()
nation = QLabel('Nation:')
nationedit = QLineEdit()
The FirstTab object contains three labels and three line editors.

vbox = QVBoxLayout()
vbox.addWidget(name)
vbox.addWidget(nameedit)
vbox.addWidget(age)
vbox.addWidget(ageedit)
vbox.addWidget(nation)
vbox.addWidget(nationedit)
vbox.addStretch()

self.setLayout(vbox)
Use the vertical box layout to position the six widgets vertically.

class SecondTab(QWidget):

...

lan_group = QGroupBox('Select Your Language')


combo = QComboBox()
list = ['Korean', 'English', 'Chinese']
combo.addItems(list)
Create a group box (lan_group) and place a combo box with three
items: ‘Korean’, ‘English’, and ‘Chinese’.

learn_group = QGroupBox('Select What You Want To Learn')


korean = QCheckBox('Korean')
english = QCheckBox('English')
chinese = QCheckBox('Chinese')
Create three check boxes in which you can make multiple choices
in the other group box (learn_group).

vbox = QVBoxLayout()
vbox.addWidget(lan_group)
vbox.addWidget(learn_group)
self.setLayout(vbox)
Place the two group boxes(lan_group, learn_group) vertically using
the vertical box.
class ThirdTab(QWidget):

def __init__(self):
super().__init__()

self.initUI()

def initUI(self):

lbl = QLabel('Terms and Conditions')


text_browser = QTextBrowser()
text_browser.setText('This is the terms and conditions')
checkbox = QCheckBox('Check the terms and conditions.')
ThirdTab objects to be located on the third tab include a label (lbl),
a text_browser, and a checkbox.
Text browsers created using QTextBrowser() are used to represent
text using hypertext.
If you want to make text editable, you must use QTextEdit().
To disable hypertext and make it non-editable, you can use the
setReadOnly() method in QTextEdit().

vbox = QVBoxLayout()
vbox.addWidget(lbl)
vbox.addWidget(text_browser)
vbox.addWidget(checkbox)

self.setLayout(vbox)
Use the vertical box layout to add labels, text browsers, and check
boxes.

Results
Figure 5-11-1. Using tab widget to make tabs (Advanced).

# 14: QPixmap
QPixmap is a widget used to deal with images.
The following file types are supported. Some image formats can
only be ‘read’.

Let’s use QPixmap to display one image on the window.

Example
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QLabel,
QVBoxLayout
from PyQt5.QtGui import QPixmap
from PyQt5.QtCore import Qt

class MyApp(QWidget):

def __init__(self):
super().__init__()

self.initUI()

def initUI(self):

pixmap = QPixmap('landscape.jpg')
lbl_img = QLabel()
lbl_img.setPixmap(pixmap)
lbl_size = QLabel('Width: '+str(pixmap.width())+', Height:
'+str(pixmap.height()))
lbl_size.setAlignment(Qt.AlignCenter)

vbox = QVBoxLayout()
vbox.addWidget(lbl_img)
vbox.addWidget(lbl_size)
self.setLayout(vbox)

self.setWindowTitle('QPixmap')
self.move(300, 300)
self.show()

if __name__ == '__main__':

app = QApplication(sys.argv)
ex = MyApp()
sys.exit(app.exec_())
One image appears on the widget window.

Description
pixmap = QPixmap('landscape.jpg')
Enter a file name and create a QPixmap object.

lbl_img = QLabel()
lbl_img.setPixmap(pixmap)
Create a label and set the pixmap as the image to be displayed on
the label using setPixmap.

lbl_size = QLabel('Width: '+str(pixmap.width())+', Height:


'+str(pixmap.height()))
lbl_size.setAlignment(Qt.AlignCenter)
width() and height() return the image’s width and height
Create a label (lbl_size) that displays width and height, and align it
to the cetner using the setAlignment method.
vbox = QVBoxLayout()
vbox.addWidget(lbl)
self.setLayout(vbox)
Create one horizontal box layout and place labels.
Use setLayout() to specify the horizontal box as the layout of the
window.

Results
Figure 5-12. Use QPixmap to display image.

# 15: QCalendarWidget

QCalendarWidget displays a calendar for the users to select a date.


The calendar is displayed monthly and is selected as the current
year, month, and date when it is first run.
For further details, check QCalendarWidget official document .

Example
import sys
from PyQt5.QtWidgets import (QApplication, QWidget, QLabel,
QVBoxLayout, QCalendarWidget)
from PyQt5.QtCore import QDate

class MyApp(QWidget):

def __init__(self):
super().__init__()

self.initUI()

def initUI(self):

cal = QCalendarWidget(self)
cal.setGridVisible(True)
cal.clicked[QDate].connect(self.showDate)

self.lbl = QLabel(self)
date = cal.selectedDate()
self.lbl.setText(date.toString())

vbox = QVBoxLayout()
vbox.addWidget(cal)
vbox.addWidget(self.lbl)

self.setLayout(vbox)

self.setWindowTitle('QCalendarWidget')
self.setGeometry(300, 300, 400, 300)
self.show()

def showDate(self, date):

self.lbl.setText(date.toString())
if __name__ == '__main__':

app = QApplication(sys.argv)
ex = MyApp()
sys.exit(app.exec_())
A calendar and a label that displays the date appear on the widget
window.

Description
cal = QCalendarWidget(self)
cal.setGridVisible(True)
cal.clicked[QDate].connect(self.showDate)
Make an object(cal) of QCalenderWidget.
If you use setGridVisible(True), a grid(line) is displayed between
dates.
It connects to the showDate method when you click a date.

self.lbl = QLabel(self)
date = cal.selectedDate()
self.lbl.setText(date.toString())
SelectedDate has the currently selected date information (default is
the current date).
Allow current date information to be displayed on the label.

vbox = QVBoxLayout()
vbox.addWidget(cal)
vbox.addWidget(self.lbl)
Use a vertical box layout to place the calendar and label vertically.

def showDate(self, date):


self.lbl.setText(date.toString())
With the showDate method, make the label text appear as the
selected date (date.toString()0 every time you click on a date.

Results
Figure 5-13. Using calendar with QCalendarWidget.

# 16: QSpinBox
The QSpinBox class provides a spinbox widget that lets you select
and control integers.
For further details, check QSpinBox official document .

Example
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QLabel,
QSpinBox, QVBoxLayout

class MyApp(QWidget):

def __init__(self):
super().__init__()

self.initUI()

def initUI(self):

self.lbl1 = QLabel('QSpinBox')
self.spinbox = QSpinBox()
self.spinbox.setMinimum(-10)
self.spinbox.setMaximum(30)
# self.spinbox.setRange(-10, 30)
self.spinbox.setSingleStep(2)
self.lbl2 = QLabel('0')

self.spinbox.valueChanged.connect(self.value_changed)
vbox = QVBoxLayout()
vbox.addWidget(self.lbl1)
vbox.addWidget(self.spinbox)
vbox.addWidget(self.lbl2)
vbox.addStretch()

self.setLayout(vbox)

self.setWindowTitle('QSpinBox')
self.setGeometry(300, 300, 300, 200)
self.show()

def value_changed(self):
self.lbl2.setText(str(self.spinbox.value()))

if __name__ == '__main__':

app = QApplication(sys.argv)
ex = MyApp()
sys.exit(app.exec_())
Two labels(self.lbl1, self.lbl2) and a spinbox widget(self.spinbox)
appears on the window.

Description
self.spinbox = QSpinBox()
self.spinbox.setMinimum(-10)
self.spinbox.setMaximum(30)
Make a QSpinBox object(self.spinbox).
You can use setMinimum() and setMaximum() methods to limit the
selection range. By default, the minimum is 0 and the maximum is
99.

# self.spinbox.setRange(-10, 30)
setRange() method is the same as setMinimum() and
setMaximum() combined.

self.spinbox.setSingleStep(2)
Use setSingleStep() to set one step as 2.
For spin box, the minimum value that can be set as a single step is
1.

self.spinbox.valueChanged.connect(self.value_changed)
Connect the signal that occurs when the value of the spinbox
widget is changed (valueChanged) to the self.value_changed
method.

vbox = QVBoxLayout()
vbox.addWidget(self.lbl1)
vbox.addWidget(self.spinbox)
vbox.addWidget(self.lbl2)
vbox.addStretch()

self.setLayout(vbox)
Use the vertical box layout to place two labels and spin-box widget
vertically, and set it as the layout of the entire widget.

def value_changed(self):
self.lbl2.setText(str(self.spinbox.value()))
When the value of the spin box changes, set the text of self.lbl2 as
the value of spinbox (self.spinbox.value()).

Results
Figure 5-14. Use QSpinBox to make spinbox widget.

# 17: QDoubleSpinBox
QDoubleSpinBox class provides a double spin box widget that lets
you select and control mistakes.
For further details, check QDoubleSpinBox official document .

Example
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QLabel,
QDoubleSpinBox, QVBoxLayout

class MyApp(QWidget):

def __init__(self):
super().__init__()

self.initUI()

def initUI(self):

self.lbl1 = QLabel('QDoubleSpinBox')
self.dspinbox = QDoubleSpinBox()
self.dspinbox.setRange(0, 100)
self.dspinbox.setSingleStep(0.5)
self.dspinbox.setPrefix('$ ')
self.dspinbox.setDecimals(1)
self.lbl2 = QLabel('$ 0.0')

self.dspinbox.valueChanged.connect(self.value_changed)

vbox = QVBoxLayout()
vbox.addWidget(self.lbl1)
vbox.addWidget(self.dspinbox)
vbox.addWidget(self.lbl2)
vbox.addStretch()
self.setLayout(vbox)

self.setWindowTitle('QDoubleSpinBox')
self.setGeometry(300, 300, 300, 200)
self.show()

def value_changed(self):
self.lbl2.setText('$ '+str(self.dspinbox.value()))

if __name__ == '__main__':
app = QApplication(sys.argv)
ex = MyApp()
sys.exit(app.exec_())
Two labels(self.lbl1, self.lbl2) and a double spin box
widget(self.spinbox) appear on the window.

Description
self.dspinbox = QDoubleSpinBox()
self.dspinbox.setRange(0, 100)
self.dspinbox.setSingleStep(0.5)
Make a QDoubleSpinBox object(self.dspinbox).
setRange() method helps you limit the range of selection. By
default, the minimum value is 0.0 and the maximum is 99.99.
Use setSingleStep() method to make a single step 0.5.

self.dspinbox.setPrefix('$ ')
self.dspinbox.setDecimals(1)
setPrefix() to sets the character that will come in front of the
number. setSuffix() makes the character come behind the number.
setDecimals() sets the number of decimal places to be displayed.
self.dspinbox.valueChanged.connect(self.value_changed)
Associate the signal that occurs when the value of the double spin
box widget is changed (valueChanged) with the self.value_changed
method.

vbox = QVBoxLayout()
vbox.addWidget(self.lbl1)
vbox.addWidget(self.dspinbox)
vbox.addWidget(self.lbl2)
vbox.addStretch()

self.setLayout(vbox)
Use the vertical box layout to place two labels and a double-spin
box widget vertically, and set it as the layout of the entire widget.

def value_changed(self):
self.lbl2.setText('$ '+str(self.dspinbox.value()))
When the value of the double spin box changes, make the text of
self.lbl2 be the value for the double spin box
(self.dspinbox.value()).

Results
Figure 5-15. Using QDoubleSpinBox for double spin box widget.

# 18: QDateEdit
The QDateEdit widget is used to let users select and edit dates.
In this example, we’ll create a QDateEdit object and set it to
display as the current date.
For further details, check QDateEdit official document .

Example
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QLabel,
QDateEdit, QVBoxLayout
from PyQt5.QtCore import QDate

class MyApp(QWidget):

def __init__(self):
super().__init__()

self.initUI()

def initUI(self):

lbl = QLabel('QDateEdit')

dateedit = QDateEdit(self)
dateedit.setDate(QDate.currentDate())
dateedit.setMinimumDate(QDate(1900, 1, 1))
dateedit.setMaximumDate(QDate(2100, 12, 31))
# dateedit.setDateRange(QDate(1900, 1, 1), QDate(2100, 12, 31))

vbox = QVBoxLayout()
vbox.addWidget(lbl)
vbox.addWidget(dateedit)
vbox.addStretch()

self.setLayout(vbox)
self.setWindowTitle('QDateEdit')
self.setGeometry(300, 300, 300, 200)
self.show()

if __name__ == '__main__':

app = QApplication(sys.argv)
ex = MyApp()
sys.exit(app.exec_())
QDateEdit appears on the window.

Description
dateedit = QDateEdit(self)
dateedit.setDate(QDate.currentDate())
dateedit.setMinimumDate(QDate(1900, 1, 1))
dateedit.setMaximumDate(QDate(2100, 12, 31))
Create a date edit widget using the QDateEdit class.
In the setDate method, type QDate.currentDate() to display the
current date when the program runs
SetMinimumDate and setMaximumDate allow you to limit the
range of dates that you can select.
The minimum date is set to September 14, 1752 by default, and the
maximum date is set to December 31, 9999.
The minimum date must be at least January 1, 100.

# dateedit.setDateRange(QDate(1900, 1, 1), QDate(2100, 12, 31))


The setDateRange method is the same as using setMinimumDate
and setMaximumDate at the same time.

vbox = QVBoxLayout()
vbox.addWidget(lbl)
vbox.addWidget(dateedit)
vbox.addStretch()

self.setLayout(vbox)
Use the vertical box layout to position the label and date editing
widget vertically and set it as the layout of the entire widget.

Results
Figure 5-16. Using QDateEdit for date editing widget.

# 19: QTimeEdit
The QTimeEdit widget allows users select and edit time.
We’ll create a QTimeEdit object in this example and set it to
display as the current time.
For further information, check QTimeEdit official document .

Example
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QLabel,
QTimeEdit, QVBoxLayout
from PyQt5.QtCore import QTime

class MyApp(QWidget):

def __init__(self):
super().__init__()

self.initUI()

def initUI(self):

lbl = QLabel('QTimeEdit')

timeedit = QTimeEdit(self)
timeedit.setTime(QTime.currentTime())
timeedit.setTimeRange(QTime(3, 00, 00), QTime(23, 30, 00))
timeedit.setDisplayFormat('hh:mm:ss')
vbox = QVBoxLayout()
vbox.addWidget(lbl)
vbox.addWidget(timeedit)
vbox.addStretch()

self.setLayout(vbox)

self.setWindowTitle('QTimeEdit')
self.setGeometry(300, 300, 300, 200)
self.show()

if __name__ == '__main__':
app = QApplication(sys.argv)
ex = MyApp()
sys.exit(app.exec_())
Time editing widget(QTimeEdit) appears on the window.

Description
timeedit = QTimeEdit(self)
timeedit.setTime(QTime.currentTime())
timeedit.setTimeRange(QTime(3, 00, 00), QTime(23, 30, 00))
Create a time edit widget using the QTimeEdit class.
Type QTime.currentTime() in the setTime method so that the
current time is displayed when the program is run.
setTimeRange allows users to limit the range of time you can
select. The minimum time is set to 00:00:00:000 milliseconds by
default, and the maximum time is set to 23:59:59:999 milliseconds.

timeedit.setDisplayFormat('hh:mm:ss')
We used setDisplayFormat method to display time in the format
‘hhh:mm:ss’.
vbox = QVBoxLayout()
vbox.addWidget(lbl)
vbox.addWidget(timeedit)
vbox.addStretch()

self.setLayout(vbox)
Use the vertical box layout to position the label and time editing
widget vertically, and set it as the layout of the entire widget.

Results
Figure 5-15. Use QTimeEdit for time editing widget.

# 20: QDateTimeEdit
QDateTimeEdit widget helps users select and edit date and time.
Let’s create a QDateTimeEdit object in the example and set it to
display current date and time.
For further details check QDateTimeEdit official document .

Example
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QLabel,
QDateTimeEdit, QVBoxLayout
from PyQt5.QtCore import QDateTime

class MyApp(QWidget):

def __init__(self):
super().__init__()

self.initUI()

def initUI(self):
lbl = QLabel('QTimeEdit')

datetimeedit = QDateTimeEdit(self)
datetimeedit.setDateTime(QDateTime.currentDateTime())
datetimeedit.setDateTimeRange(QDateTime(1900, 1, 1, 00, 00, 00),
QDateTime(2100, 1, 1, 00, 00, 00))
datetimeedit.setDisplayFormat('yyyy.MM.dd hh:mm:ss')

vbox = QVBoxLayout()
vbox.addWidget(lbl)
vbox.addWidget(datetimeedit)
vbox.addStretch()

self.setLayout(vbox)

self.setWindowTitle('QDateTimeEdit')
self.setGeometry(300, 300, 300, 200)
self.show()

if __name__ == '__main__':
app = QApplication(sys.argv)
ex = MyApp()
sys.exit(app.exec_())
QDateTimeEdit appears on the window.

Description
datetimeedit = QDateTimeEdit(self)
datetimeedit.setDateTime(QDateTime.currentDateTime())
datetimeedit.setDateTimeRange(QDateTime(1900, 1, 1, 00, 00, 00),
QDateTime(2100, 1, 1, 00, 00, 00))
Use QDateTimeEdit class to make a date,time editing widget
(datetimeedit).
Type QDateTime.currentDateTime() in the setDateTime method so
that current time and date is displayed when the program runs.
SetDateTimeRange allows you to limit the range of time you can
select.

datetimeedit.setDisplayFormat('yyyy.MM.dd hh:mm:ss')
Use the setDisplayFormat method to display time in the form
‘yyyy.MM.dd hh:mm:ss’.

vbox = QVBoxLayout()
vbox.addWidget(lbl)
vbox.addWidget(datetimeedit)
vbox.addStretch()

self.setLayout(vbox)
Use the vertical box layout to position the label and date,time
editing widget vertically and set it as the layout of the entire
widget.

Results

Figure 5-18. Use QDateTimeEdit for date,time editing widget.

# 21: QTextBrowser
The QTextBrowser class provides a rich-text browser with
hypertext navigation.
This class is read-only, and as an extension of QTextEdit, links to
hypertext documents are available.
To use the editable rich-text editor, you must use QTextEdit. Also,
to use a text browser without hypertext navigation, use QTextEdit
setReadOnly() to make editing impossible.
You can use QLabel to display short rich text.
Example
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QLineEdit,
QTextBrowser, QPushButton, QVBoxLayout

class MyApp(QWidget):

def __init__(self):
super().__init__()

self.initUI()

def initUI(self):

self.le = QLineEdit()
self.le.returnPressed.connect(self.append_text)

self.tb = QTextBrowser()
self.tb.setAcceptRichText(True)
self.tb.setOpenExternalLinks(True)

self.clear_btn = QPushButton('Clear')
self.clear_btn.pressed.connect(self.clear_text)

vbox = QVBoxLayout()
vbox.addWidget(self.le, 0)
vbox.addWidget(self.tb, 1)
vbox.addWidget(self.clear_btn, 2)

self.setLayout(vbox)

self.setWindowTitle('QTextBrowser')
self.setGeometry(300, 300, 300, 300)
self.show()
def append_text(self):

text = self.le.text()
self.tb.append(text)
self.le.clear()

def clear_text(self):

self.tb.clear()

if __name__ == '__main__':

app = QApplication(sys.argv)
ex = MyApp()
sys.exit(app.exec_())
The TimeEdit widget appears on the window.

Description
self.le = QLineEdit()
self.le.returnPressed.connect(self.append_text)
We made a line editor. Press the Enter key to call the append_text
method.

self.tb = QTextBrowser()
self.tb.setAcceptRichText(True)
self.tb.setOpenExternalLinks(True)
We created a text browser with QTextBrowser() class.
If you set setAcceptRichText() to True, you can use rich text.
(Although it’s True by default and hence unnecessary).
If you set SetOpenExternalLinks() to True, you can connect to an
external link.
self.clear_btn = QPushButton('Clear')
self.clear_btn.pressed.connect(self.clear_text)
Clicking clear_btn calls the clear_text method.

def append_text(self):

text = self.le.text()
self.tb.append(text)
self.le.clear()
The append_text method allows text (self.le.text() written in the
line editor to be appended to a text browser (self.tb).
When text is added to the text browser, use the clear method to
remove text from the line editor.

def clear_text(self):

self.tb.clear()
When the clear_text method is called, use the clear method to
remove text from the text browser (self.tb).

Plain Text
<b>Bold</b>
<i>Italic</i>
<p style="color: red">Red</p>
<p style="font-size: 20px">20px</p>
<a href="https://www.naver.com">Naver</a>
In the Line Editor, type the above text in order and add it to the text
browser using the Enter key.

Results
Figure 5-19. Use QTextBrowser to browse text.

# 22: QTextBrowser (Advanced)


Now let’s use web crawling to seek out BBC News search results
headlines.

Example
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QLineEdit,
QPushButton, QLabel, QTextBrowser, QGridLayout
import requests
from bs4 import BeautifulSoup

class MyApp(QWidget):

def __init__(self):
super().__init__()

self.initUI()

def initUI(self):

self.le = QLineEdit()
self.le.setPlaceholderText('Enter your search word')
self.le.returnPressed.connect(self.crawl_news)

self.btn = QPushButton('Search')
self.btn.clicked.connect(self.crawl_news)

self.lbl = QLabel('')

self.tb = QTextBrowser()
self.tb.setAcceptRichText(True)
self.tb.setOpenExternalLinks(True)

grid = QGridLayout()
grid.addWidget(self.le, 0, 0, 1, 3)
grid.addWidget(self.btn, 0, 3, 1, 1)
grid.addWidget(self.lbl, 1, 0, 1, 4)
grid.addWidget(self.tb, 2, 0, 1, 4)

self.setLayout(grid)

self.setWindowTitle('Web Crawler')
self.setGeometry(100, 100, 700, 450)
self.show()

def crawl_news(self):
search_word = self.le.text()

if search_word:
self.lbl.setText('BBC Search Results for "' + search_word + '"')
self.tb.clear()
url_search = 'https://www.bbc.co.uk/search?q='
url = url_search + search_word
r = requests.get(url)
html = r.content
soup = BeautifulSoup(html, 'html.parser')
titles_html = soup.select('.search-results > li > article > div > h1 >
a')

for i in range(len(titles_html)):
title = titles_html[i].text
link = titles_html[i].get('href')
self.tb.append(str(i+1) + '. ' + title + ' (' + '<a href="' + link +
'">Link</a>' + ')')

if __name__ == '__main__':

app = QApplication(sys.argv)
ex = MyApp()
sys.exit(app.exec_())
Enter a search term and click the button to output the BBC News
search results and links to a text browser.

Description
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QLineEdit,
QPushButton, QLabel, QTextBrowser, QGridLayout
import requests
from bs4 import BeautifulSoup
In addition to the modules related to PyQt5, open the requests,
BeautifulSoup libraries required for crawling.

self.le = QLineEdit()
self.le.setPlaceholderText('Enter your search word')
self.le.returnPressed.connect(self.crawl_news)
Use QLineEdit() to create a line editor for entering dates.
Use setPlaceholderText to make the line editor have ‘Enter your
search word’ displayed.
returnPressed is the signal that’s generated when the Enter key is
pressed. Connect to the crawl_news method.

self.btn = QPushButton('Search')
self.btn.clicked.connect(self.crawl_news)
Create the ‘Search’ button. Clicking the button also invokes the
crawl_news method.

self.tb = QTextBrowser()
self.tb.setAcceptRichText(True)
self.tb.setOpenExternalLinks(True)
Create a text browser using QTextBrowser() class.
The setAcceptRichText, which allows formatted text, is set to True
by default so you don’t have to create it.
Allow external links using setOpenExternalLinks().

grid = QGridLayout()
grid.addWidget(self.le, 0, 0, 1, 3)
grid.addWidget(self.btn, 0, 3, 1, 1)
grid.addWidget(self.lbl, 1, 0, 1, 4)
grid.addWidget(self.tb, 2, 0, 1, 4)

self.setLayout(grid)
Using the grid layout, place the line editor(self.le), ‘Search’
button(self.btn), label(self), and text browser (self.tb) in the
appropriate location.
The first parameter in addWidget stands for the widget you want to
add, the second and third for the location of the row and column,
and the third and fourth for the space in which the row and column
occupy.

def crawl_news(self):
search_word = self.le.text()

if search_word:
self.lbl.setText('BBC Search Results for "' + search_word + '"')
self.tb.clear()
Assign the text entered in the line editor to search_word. If there is
a search term entered, make ‘BBC Search Results for
“search_word“‘ show on the label.
Use self.tb.clear() to remove the text previously displayed in the
text browser.

url_search = 'https://www.bbc.co.uk/search?q='
url = url_search + search_word
r = requests.get(url)
html = r.content
soup = BeautifulSoup(html, 'html.parser')
titles_html = soup.select('.search-results > li > article > div > h1 > a')
Go to that address and select the text that corresponds to the title of
your news search results.

for i in range(len(titles_html)):
title = titles_html[i].text
link = titles_html[i].get('href')
self.tb.append(str(i+1) + '. ' + title + ' (' + '<a href="' + link +
'">Link</a>' + ')')
titles_html[i].text is the text within a tag, and
titles_html[i].get(‘href’) is the link address for a tag.
Add a title and link to the news in the text browser.

Results
Figure 5-19-1. Using BeautifulSoup to crawl BBC News search
results.

# 23: QTextEdit
The QTextEdit class provides an editor that lets you edit and
display both plain text and rich text.
Let’s use two labels and a text editor to create a simple program
that displays the number of words.

Example
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QLabel,
QTextEdit, QVBoxLayout

class MyApp(QWidget):

def __init__(self):
super().__init__()

self.initUI()

def initUI(self):

self.lbl1 = QLabel('Enter your sentence:')


self.te = QTextEdit()
self.te.setAcceptRichText(False)
self.lbl2 = QLabel('The number of words is 0')

self.te.textChanged.connect(self.text_changed)
vbox = QVBoxLayout()
vbox.addWidget(self.lbl1)
vbox.addWidget(self.te)
vbox.addWidget(self.lbl2)
vbox.addStretch()

self.setLayout(vbox)

self.setWindowTitle('QTextEdit')
self.setGeometry(300, 300, 300, 200)
self.show()

def text_changed(self):

text = self.te.toPlainText()
self.lbl2.setText('The number of words is ' + str(len(text.split())))

if __name__ == '__main__':
app = QApplication(sys.argv)
ex = MyApp()
sys.exit(app.exec_())
When you type text in a text editor, it displays the number of words
below.

Description
self.lbl1 = QLabel('Enter your sentence:')
self.te = QTextEdit()
self.te.setAcceptRichText(False)
self.lbl2 = QLabel('The number of words is 0')
We used QTextEdit() class to create a text editor.
If you set setAcceptRichText as False, it perceives everything as
plain text.
The label below shows the number of words.

self.te.textChanged.connect(self.text_changed)
Whenever the text in the text editor is modified, the text_changed
method is called.

self.clear_btn = QPushButton('Clear')
self.clear_btn.pressed.connect(self.clear_text)
If you click clear_btn, the clear_text method is called.

vbox = QVBoxLayout()
vbox.addWidget(self.lbl1)
vbox.addWidget(self.te)
vbox.addWidget(self.lbl2)
vbox.addStretch()

self.setLayout(vbox)
Using the vertical box layout, place two labels and one text editor
vertically.

def text_changed(self):

text = self.te.toPlainText()
self.lbl2.setText('The number of words is ' + str(len(text.split())))
When the text_changed method is called, use the toPlainText()
method to save the text in the text variable.
split() changes the words in the string into a list form.
len(text.split()) is the number of words in the text.
Use setText() to display the number of words on the second label.

Results
Figure 5-20. Counting number of words using QTextEdit.
PART 5: PyQt5 Dialog

# 1: QInputDialog
QInputDialog is a dialog that you use to enter simple values.
Input values can be numbers, strings, or items selected in the list.
( QInputDialog official document )
Five useful functions are provided according to the type of input
value as follows.

getText()
getMultiLineText()
getInt()
getDouble()
getItem()

In this example we’ll use getText() method.

Example
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton,
QLineEdit, QInputDialog

class MyApp(QWidget):

def __init__(self):
super().__init__()
self.initUI()

def initUI(self):

self.btn = QPushButton('Dialog', self)


self.btn.move(30, 30)
self.btn.clicked.connect(self.showDialog)

self.le = QLineEdit(self)
self.le.move(120, 35)

self.setWindowTitle('Input dialog')
self.setGeometry(300, 300, 300, 200)
self.show()

def showDialog(self):

text, ok = QInputDialog.getText(self, 'Input Dialog', 'Enter your


name:')

if ok:
self.le.setText(str(text))

if __name__ == '__main__':

app = QApplication(sys.argv)
ex = MyApp()
sys.exit(app.exec_())
We created a QPushButton and QLineEdit widget. If you press the
button, the Input dialog appears and displays the entered text on the
QLineEdit widget.

Description
text, ok = QInputDialog.getText(self, 'Input Dialog', 'Enter your name:')
This code shows you the Input dialog window.
The second parameter stands for the title of the dialog window, and
the third parameter stands for the message that will be displayed
inside the dialog window. The Input dialogue restores the entered
text and the Boolean value.
If you press the ‘OK’ button after entering the text, theBoolean
value becomes True; if you press the ‘Cancel’ button, the value
becomes False.
if ok:
self.le.setText(str(text))
Let the entered values appear in the QLineEdit widget through the
setText() method.

Results
Figure 6-1. Input dialog.

# 2: QColorDialog
QColorDialog is a dialog where you can select the color.
( QColorDialog official document )

Example
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton,
QFrame, QColorDialog
from PyQt5.QtGui import QColor

class MyApp(QWidget):

def __init__(self):
super().__init__()

self.initUI()

def initUI(self):
col = QColor(0, 0, 0)

self.btn = QPushButton('Dialog', self)


self.btn.move(30, 30)
self.btn.clicked.connect(self.showDialog)

self.frm = QFrame(self)
self.frm.setStyleSheet('QWidget { background-color: %s }' %
col.name())
self.frm.setGeometry(130, 35, 100, 100)

self.setWindowTitle('Color Dialog')
self.setGeometry(300, 300, 250, 180)
self.show()

def showDialog(self):

col = QColorDialog.getColor()

if col.isValid():
self.frm.setStyleSheet('QWidget { background-color: %s }' %
col.name())

if __name__ == '__main__':

app = QApplication(sys.argv)
ex = MyApp()
sys.exit(app.exec_())
First, create a push button and a QFrame, and set the background
color of the QFrame widget to black.
Use QColorDialog to change the background color.

Description
col = QColor(0, 0, 0)
Use QColor to make black for background color.

col = QColorDialog.getColor()
Pop up QColorDialog, and use getColor() method to save the color.

if col.isValid():
self.frm.setStyleSheet('QWidget { background-color: %s }' % col.name())
If you select the color and press the ‘OK’ button, the Boolean value
of col.isValid() becomes True; if you press the ‘Cancel’ button, the
Boolean value becomes False.
The selected color is set as the background color of the frame.

Results
Figure 6-2. Color dialog.

# 3: QFontDialog
QFontDialog is a dialog that helps you select the font.
( QFontDialog official document )

Example
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, \
QPushButton, QSizePolicy, QLabel, QFontDialog

class MyApp(QWidget):

def __init__(self):
super().__init__()
self.initUI()

def initUI(self):

btn = QPushButton('Dialog', self)


btn.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
btn.move(20, 20)
btn.clicked.connect(self.showDialog)

vbox = QVBoxLayout()
vbox.addWidget(btn)

self.lbl = QLabel('The quick brown fox jumps over the lazy dog', self)
self.lbl.move(130, 20)

vbox.addWidget(self.lbl)
self.setLayout(vbox)

self.setWindowTitle('Font Dialog')
self.setGeometry(300, 300, 250, 180)
self.show()

def showDialog(self):

font, ok = QFontDialog.getFont()

if ok:
self.lbl.setFont(font)

if __name__ == '__main__':

app = QApplication(sys.argv)
ex = MyApp()
sys.exit(app.exec_())
We made a push button and a lable. You can change the label’s font
using QFontDialog.

Description
font, ok = QFontDialog.getFont()
Pop up QFontDialog and use getFont() method to restore the
selected font and Boolean value.
Like the previous example, you get True if you click the ‘OK’
button, False if you click the ‘Cancel’ button.

if ok:
self.lbl.setFont(font)
Use setFont() method to set the selected font as the label’s font.

Results
Figure 6-3. Font dialog.

# 4: QFileDialog
QFileDialog is a dialog that allows users to select files or paths.
Users can open the selected files to modify or save them.
( QFileDialog official document )

Example
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QTextEdit,
QAction, QFileDialog
from PyQt5.QtGui import QIcon

class MyApp(QMainWindow):

def __init__(self):
super().__init__()

self.initUI()

def initUI(self):
self.textEdit = QTextEdit()
self.setCentralWidget(self.textEdit)
self.statusBar()

openFile = QAction(QIcon('open.png'), 'Open', self)


openFile.setShortcut('Ctrl+O')
openFile.setStatusTip('Open New File')
openFile.triggered.connect(self.showDialog)

menubar = self.menuBar()
menubar.setNativeMenuBar(False)
fileMenu = menubar.addMenu('&File')
fileMenu.addAction(openFile)

self.setWindowTitle('File Dialog')
self.setGeometry(300, 300, 300, 200)
self.show()

def showDialog(self):

fname = QFileDialog.getOpenFileName(self, 'Open file', './')

if fname[0]:
f = open(fname[0], 'r')

with f:
data = f.read()
self.textEdit.setText(data)

if __name__ == '__main__':

app = QApplication(sys.argv)
ex = MyApp()
sys.exit(app.exec_())
You have placed the Menu Bar, Text Edit, and Status Bar widgets.
The menu contains an ‘Open’ menu for selecting files. Bring the
contents of the selected file into the Text Edit widget.

Description
fname = QFileDialog.getOpenFileName(self, 'Open file', './')
Pop up QFileDialog, and use getOpenFileName() method to select
the file.
The third parameter allows you to set the default path. Also all files
(*) are to be open by default.

if fname[0]:
f = open(fname[0], 'r')

with f:
data = f.read()
self.textEdit.setText(data)
Read the selected file and bring it to the Edit Text widget via the
setText() method.

Results
Figure 6-4. File Dialog.

# 5: QMessageBox
The QMessageBox class provides users information or a window
for Q&A.
The message box is often used to check for an action.
( QMessageBox official document )
The message box displays the default text that describes the
situation to the user. Then it can deliver information or display text
that asks for the user’s opinions.
Finally it can display further details about the situation.
You can use setText()/setInformativeText()/setDetailedText()
methods to display the mentioned texts.

Example
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QMessageBox

class MyApp(QWidget):

def __init__(self):
super().__init__()

self.initUI()

def initUI(self):
self.setWindowTitle('QMessageBox')
self.setGeometry(300, 300, 300, 200)
self.show()

def closeEvent(self, event):

reply = QMessageBox.question(self, 'Message', 'Are you sure to quit?',


QMessageBox.Yes | QMessageBox.No,
QMessageBox.No)

if reply == QMessageBox.Yes:
event.accept()
else:
event.ignore()

if __name__ == '__main__':

app = QApplication(sys.argv)
ex = MyApp()
sys.exit(app.exec_())
Now when you close the window, a message box will appear to
confirm your actino.

Description
When you close QWidget, QCloseEvent is created and sent to the
widget.
To edit the widget’s actions, you need to edit closeEvent() event
handler.

reply = QMessageBox.question(self, 'Message', 'Are you sure to quit?',


QMessageBox.Yes | QMessageBox.No,
QMessageBox.No)
The second parameter enters the strings on the title bar(‘Message’),
and the third parameter enters the strings to be shown on the
dialog(‘Are you sure to quit?’).
The fourth decides the type of button to be shown on the dialog,
and finally, the default button.
If you set it as QMessageBox.No, the ‘No’ button is selected when
the message box appears.
The restore value is saved in reply variable.

if reply == QMessageBox.Yes:
event.accept()
else:
event.ignore()
If you click the ‘Yes’ button, the event is accepted and the widget is
closed.
If you click the ‘No’ button, the event is ignored and the widget
does not close.

Results

Figure 6-5. Message box.


PART 6: PyQt5 Signals and slots
# 1: Connecting signal and slot
Let’s create a program that displays the values adjusted with the
dial widget on the screen.
Signals that occur when the value of the dial changes are connected
to slots that display numbers on the LCD screen.

Example
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QLCDNumber,
QDial, QVBoxLayout

class MyApp(QWidget):

def __init__(self):
super().__init__()

self.initUI()

def initUI(self):

lcd = QLCDNumber(self)
dial = QDial(self)

vbox = QVBoxLayout()
vbox.addWidget(lcd)
vbox.addWidget(dial)
self.setLayout(vbox)

dial.valueChanged.connect(lcd.display)

self.setWindowTitle('Signal and Slot')


self.setGeometry(300, 300, 200, 200)
self.show()

if __name__ == '__main__':

app = QApplication(sys.argv)
ex = MyApp()
sys.exit(app.exec_())
When you rotate the dial, the LCD displays numbers according to
the value.

Description
lcd = QLCDNumber(self)
dial = QDial(self)
The QLCDNumber widget displays numbers like LCD screens.
QDial is a widget that rotates the dial to adjust its value.

vbox = QVBoxLayout()
vbox.addWidget(lcd)
vbox.addWidget(dial)
self.setLayout(vbox)
Create a vertical box layout (see the box layout page) to include the
QLCDNumber and QDial widgets. Then set it as the layout of the
MyApp widget.

dial.valueChanged.connect(lcd.display)
The QDial widget has several signals. (see the QSlider, QDial
page)
Here you connect the valueChanged signal to the display slot on
the lcd. The display slot takes the number and displays it on the
QLCDNumber widget.
Here the dial is the sender of the signal and the lcd is the receiver
of the signal. Slot is a method that embodies how to react to a
signal.

Results

Figure 7-1. Connecting signal and slot.

# 2: Make event handler


The function used in PyQt for event (signal) processing is called
event handler (slot).
Let’s define a function (slot) that changes the size of the window
when a signal occurs for pressing the ‘Big’ and ‘Small’ buttons.
Example
import sys
from PyQt5.QtWidgets import (QApplication, QWidget, QLCDNumber,
QDial, QPushButton, QVBoxLayout, QHBoxLayout)

class MyApp(QWidget):

def __init__(self):
super().__init__()

self.initUI()

def initUI(self):

lcd = QLCDNumber(self)
dial = QDial(self)
btn1 = QPushButton('Big', self)
btn2 = QPushButton('Small', self)

hbox = QHBoxLayout()
hbox.addWidget(btn1)
hbox.addWidget(btn2)

vbox = QVBoxLayout()
vbox.addWidget(lcd)
vbox.addWidget(dial)
vbox.addLayout(hbox)
self.setLayout(vbox)

dial.valueChanged.connect(lcd.display)
btn1.clicked.connect(self.resizeBig)
btn2.clicked.connect(self.resizeSmall)

self.setWindowTitle('Signal and Slot')


self.setGeometry(200, 200, 200, 250)
self.show()

def resizeBig(self):
self.resize(400, 500)

def resizeSmall(self):
self.resize(200, 250)

if __name__ == '__main__':

app = QApplication(sys.argv)
ex = MyApp()
sys.exit(app.exec_())
The window can be enlarged and reduced by pressing the ‘Big’ and
‘Small’ buttons.

Description
btn1.clicked.connect(self.resizeBig)
btn2.clicked.connect(self.resizeSmall)
btn1 and btn2 are connected to resizeBig, resizeSmall slots,
respectively.

def resizeBig(self):
self.resize(400, 500)

def resizeSmall(self):
self.resize(200, 250)
The resizeBig() method extends the screen size to 400px by 500px,
and the resizeSmall() method reduces the screen size to 200px by
250px.

Results
Figure 7-2. Make event handler.
# 3: Reimplement event handler
Frequently used event handlers are often already created, such as:
Event Handler Description
keyPressEvent Works when you press the keyboard.
keyReleaseEvent Works when you release the keyboard.
mouseDoubleClickEvent Works when you double-click.
mouseMoveEvent Works when you move the mouse.
mousePressEvent Works when you press the mouse.
mouseReleaseEvent Works when you release the mouse.
moveEvent Works when the widget moves.
resizeEvent Works when you resize the widget.

Let’s modify the keyPressEvent event handler to implement the


ability to shut down, maximize, and adjust the size of the widget
when a specific key is pressed.

Example
import sys
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QApplication, QWidget

class MyApp(QWidget):

def __init__(self):
super().__init__()

self.initUI()

def initUI(self):
self.setWindowTitle('Reimplementing event handler')
self.setGeometry(300, 300, 300, 200)
self.show()

def keyPressEvent(self, e):

if e.key() == Qt.Key_Escape:
self.close()
elif e.key() == Qt.Key_F:
self.showFullScreen()
elif e.key() == Qt.Key_N:
self.showNormal()

if __name__ == '__main__':

app = QApplication(sys.argv)
ex = MyApp()
sys.exit(app.exec_())
The event handler has been reimplemented so that clicking the ‘esc’
(escape), ‘F’ and ‘N’ makes the window close, maximize, or
become average size.

Description
def keyPressEvent(self, e):

if e.key() == Qt.Key_Escape:
self.close()
elif e.key() == Qt.Key_F:
self.showFullScreen()
elif e.key() == Qt.Key_N:
self.showNormal()
The keyPressEvent event handler receives events from the
keyboard as input.
e.key() restores which key has been pressed or released.
‘If you press the ‘esc’ key, the widget will exit through self.close().
If you press the ‘F’ or ‘N’ key, the widget will be maximized or
back to its average size.

# 4: Reimplemente event handler


2
This time, we will use mouseMoveEvent to track and print the
position of the mouse.
Example
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QLabel

class MyApp(QWidget):

def __init__(self):
super().__init__()

self.initUI()

def initUI(self):

x=0
y=0

self.text = 'x: {0}, y: {1}'.format(x, y)


self.label = QLabel(self.text, self)
self.label.move(20, 20)
self.setMouseTracking(True)

self.setWindowTitle('Reimplementing event handler')


self.setGeometry(300, 300, 300, 200)
self.show()

def mouseMoveEvent(self, e):

x = e.x()
y = e.y()

text = 'x: {0}, y: {1}'.format(x, y)


self.label.setText(text)
self.label.adjustSize()

if __name__ == '__main__':

app = QApplication(sys.argv)
ex = MyApp()
sys.exit(app.exec_())
Moving the mouse within the widget will result in an event and
output the position of the mouse through the reimplemented event
handler.

Description
self.text = 'x: {0}, y: {1}'.format(x, y)
self.label = QLabel(self.text, self)
self.label.move(20, 20)
Save the value of x, y as self.text and the text for self.label.
Move the position as much as x=20, y=20.

self.setMouseTracking(True)
Set setMouseTracking to True to track the mouse position.
Default is setMouseTracking (false), and mouseEvent occurs only
when you click or release the mouse button.

def mouseMoveEvent(self, e):

x = e.x()
y = e.y()

text = 'x: {0}, y: {1}'.format(x, y)


self.label.setText(text)
self.label.adjustSize()
Event e is an object that has information about the event. This
event object depends on the type of event that is generated.
e.x(), e.y() restores the position of the mouse cursor when an event
occurs within the widget.
If you set it to e.globalX(), e.globalY(), it will restore the position
of the mouse cursor in the entire screen.
Use the self.label.adjustSize() method to automatically resize the
label.

Results

Figure 7-4. Reimplement event handler 2.


# 5: User defined signal
In addition to the specified signals, you can also create and use new
signals.
In this example, we’ll use pyqtSignal() to create a custom signal
and make it become released when a particular event occurs.

Example
import sys
from PyQt5.QtCore import pyqtSignal, QObject
from PyQt5.QtWidgets import QApplication, QMainWindow

class Communicate(QObject):

closeApp = pyqtSignal()

class MyApp(QMainWindow):

def __init__(self):
super().__init__()

self.initUI()

def initUI(self):

self.c = Communicate()
self.c.closeApp.connect(self.close)

self.setWindowTitle('Emitting Signal')
self.setGeometry(300, 300, 300, 200)
self.show()
def mousePressEvent(self, e):

self.c.closeApp.emit()

if __name__ == '__main__':

app = QApplication(sys.argv)
ex = MyApp()
sys.exit(app.exec_())
We made a signal called closeApp.
This signal occurs when you click the mouse and is connected to
the close() slot in the QMainWindow to quit the program.

Description
class Communicate(QObject):

closeApp = pyqtSignal()
We created a signal called closeApp as a property of the
Communicate class with pyqtSignal().

self.c = Communicate()
self.c.closeApp.connect(self.close)
The closeApp signal in the Communicate class connects to the
close() slot in the MyApp class.

def mousePressEvent(self, e):

self.c.closeApp.emit()
Using the mousePressEvent event handler, we made the closeApp
signal get released when the mouse was clicked.
PART 7: Examples and Projects

# 1: Creating a simple browser using


PyQt5
In this article we will see how we can create a simple browser
using PyQt5.
Web browser is a software application for accessing information
on the World Wide Web. When a user requests a web page from a
particular website, the web browser retrieves the necessary content
from a web server and then displays the page on the screen.
PyQt5 is cross-platform GUI toolkit, a set of python bindings for
Qt v5. One can develop an interactive desktop application with so
much ease because of the tools and simplicity provided by this
library.
GUI Implementation steps :
1. Create a main window
2. Create a QWebEngineView object and add it as the central
widget to the main window
3. Add Status bar to the main window
4. Create a toolbar and add navigation button and the line edit to
show the url, below is hot the toolbar will look like
Back-End Implementation Steps :
1. Add update url action to QWebEngineView object when url is
changed.
2. Inside the update url action change the url of url bar and change
cursor position
3. Add another update title action to the QWebEngineView object
when loading is finished
4. Inside the update title method update the title of the window as
the page title
5. Add actions to the navigation buttons using the build-in
functions of the QWebEngineView object for reload, back, stop and
forward buttons
6. Add action to the home button and inside the action change the
url to google.com
7. Add action to the line edit when return key is pressed
8. Inside the line edit action get the text and convert this text to the
QUrl object and set the scheme if it is null and set this url to the
QWebEngineView object

Below is the implementation

Python3

# importing required libraries

from PyQt5.QtCore import *

from PyQt5.QtWidgets import *


from PyQt5.QtGui import *

from PyQt5.QtWebEngineWidgets import *

from PyQt5.QtPrintSupport import *

import os

import sys

# creating main window class

class MainWindow(QMainWindow):

# constructor

def __init__(self, *args, **kwargs):

super(MainWindow, self).__init__(*args, **kwargs)

# creating a QWebEngineView

self.browser = QWebEngineView()

# setting default browser url as google

self.browser.setUrl(QUrl("http://google.com"))

# adding action when url get changed

self.browser.urlChanged.connect(self.update_urlbar)

# adding action when loading is finished

self.browser.loadFinished.connect(self.update_title)
# set this browser as central widget or main window

self.setCentralWidget(self.browser)

# creating a status bar object

self.status = QStatusBar()

# adding status bar to the main window

self.setStatusBar(self.status)

# creating QToolBar for navigation

navtb = QToolBar("Navigation")

# adding this tool bar tot he main window

self.addToolBar(navtb)

# adding actions to the tool bar

# creating a action for back

back_btn = QAction("Back", self)

# setting status tip

back_btn.setStatusTip("Back to previous page")

# adding action to the back button

# making browser go back

back_btn.triggered.connect(self.browser.back)

# adding this action to tool bar


navtb.addAction(back_btn)

# similarly for forward action

next_btn = QAction("Forward", self)

next_btn.setStatusTip("Forward to next page")

# adding action to the next button

# making browser go forward

next_btn.triggered.connect(self.browser.forward)

navtb.addAction(next_btn)

# similarly for reload action

reload_btn = QAction("Reload", self)

reload_btn.setStatusTip("Reload page")

# adding action to the reload button

# making browser to reload

reload_btn.triggered.connect(self.browser.reload)

navtb.addAction(reload_btn)

# similarly for home action

home_btn = QAction("Home", self)

home_btn.setStatusTip("Go home")

home_btn.triggered.connect(self.navigate_home)

navtb.addAction(home_btn)
# adding a separator in the tool bar

navtb.addSeparator()

# creating a line edit for the url

self.urlbar = QLineEdit()

# adding action when return key is pressed

self.urlbar.returnPressed.connect(self.navigate_to_url)

# adding this to the tool bar

navtb.addWidget(self.urlbar)

# adding stop action to the tool bar

stop_btn = QAction("Stop", self)

stop_btn.setStatusTip("Stop loading current page")

# adding action to the stop button

# making browser to stop

stop_btn.triggered.connect(self.browser.stop)

navtb.addAction(stop_btn)

# showing all the components

self.show()

# method for updating the title of the window

def update_title(self):
title = self.browser.page().title()

self.setWindowTitle("% s - Geek Browser" % title)

# method called by the home action

def navigate_home(self):

# open the google

self.browser.setUrl(QUrl("http://www.google.com"))

# method called by the line edit when return key is pressed

def navigate_to_url(self):

# getting url and converting it to QUrl object

q = QUrl(self.urlbar.text())

# if url is scheme is blank

if q.scheme() == "":

# set url scheme to html

q.setScheme("http")

# set the url to the browser

self.browser.setUrl(q)

# method for updating url

# this method is called by the QWebEngineView object


def update_urlbar(self, q):

# setting text to the url bar

self.urlbar.setText(q.toString())

# setting cursor position of the url bar

self.urlbar.setCursorPosition(0)

# creating a pyQt5 application

app = QApplication(sys.argv)

# setting name to the application

app.setApplicationName("Geek Browser")

# creating a main window object

window = MainWindow()

# loop

app.exec_()

# 2: Timer Application using PyQt5


In this article we will see how we can create a timer application in
PyQt5. A timer is a specialized type of clock used for measuring
specific time intervals, for the given time we have to decrease the
time until times become zero i.e counting downwards.
GUI Implementation steps : 1. Create a push button to open pop
up for getting time and set its geometry 2. Create label to show
time and complete status 3. Set label geometry, font size and align
its text to center 4. Create three push button for starting the timer,
pausing the timer and for resetting the timer 5. Set the geometry of
each button Back-end Implementation steps : 1. Create count
variable and flag to know if counter is stopped or running 2. Add
action to each button 3. Inside the get second button action get the
value of second using input dialog box and make the flag false 4.
Inside the start action make flag true but if count is zero make if
false 5. Inside pause action make flag false 6. Inside the reset
action make flag false, set count value to zero and set text to the
label 7. Make a timer object which calls its method after every 100
milliseconds 8. Inside the timer action check for the flag then
decrement the value of count and set text to the label
Below is the implementation

Python3

# importing libraries

from PyQt5.QtWidgets import *

from PyQt5 import QtCore, QtGui

from PyQt5.QtGui import *

from PyQt5.QtCore import *

import sys

class Window(QMainWindow):
def __init__(self):

super().__init__()

# setting title

self.setWindowTitle("Python ")

# setting geometry

self.setGeometry(100, 100, 400, 600)

# calling method

self.UiComponents()

# showing all the widgets

self.show()

# method for widgets

def UiComponents(self):

# variables

# count variable

self.count = 0

# start flag

self.start = False

# creating push button to get time in seconds


button = QPushButton("Set time(s)", self)

# setting geometry to the push button

button.setGeometry(125, 100, 150, 50)

# adding action to the button

button.clicked.connect(self.get_seconds)

# creating label to show the seconds

self.label = QLabel("//TIMER//", self)

# setting geometry of label

self.label.setGeometry(100, 200, 200, 50)

# setting border to the label

self.label.setStyleSheet("border : 3px solid black")

# setting font to the label

self.label.setFont(QFont('Times', 15))

# setting alignment to the label

self.label.setAlignment(Qt.AlignCenter)

# creating start button

start_button = QPushButton("Start", self)


# setting geometry to the button

start_button.setGeometry(125, 350, 150, 40)

# adding action to the button

start_button.clicked.connect(self.start_action)

# creating pause button

pause_button = QPushButton("Pause", self)

# setting geometry to the button

pause_button.setGeometry(125, 400, 150, 40)

# adding action to the button

pause_button.clicked.connect(self.pause_action)

# creating reset button

reset_button = QPushButton("Reset", self)

# setting geometry to the button

reset_button.setGeometry(125, 450, 150, 40)

# adding action to the button

reset_button.clicked.connect(self.reset_action)

# creating a timer object

timer = QTimer(self)
# adding action to timer

timer.timeout.connect(self.showTime)

# update the timer every tenth second

timer.start(100)

# method called by timer

def showTime(self):

# checking if flag is true

if self.start:

# incrementing the counter

self.count -= 1

# timer is completed

if self.count == 0:

# making flag false

self.start = False

# setting text to the label

self.label.setText("Completed !!!! ")

if self.start:

# getting text from count


text = str(self.count / 10) + " s"

# showing text

self.label.setText(text)

# method called by the push button

def get_seconds(self):

# making flag false

self.start = False

# getting seconds and flag

second, done = QInputDialog.getInt(self, 'Seconds', 'Enter Seconds:')

# if flag is true

if done:

# changing the value of count

self.count = second * 10

# setting text to the label

self.label.setText(str(second))

def start_action(self):

# making flag true


self.start = True

# count = 0

if self.count == 0:

self.start = False

def pause_action(self):

# making flag false

self.start = False

def reset_action(self):

# making flag false

self.start = False

# setting count value to 0

self.count = 0

# setting label text

self.label.setText("//TIMER//")

# create pyqt5 app


App = QApplication(sys.argv)

# create the instance of our Window

window = Window()

# start the app

sys.exit(App.exec())

# 3: Create Paint Application –


PyQt5

There are so many options provided by Python to develop GUI


application and PyQt5 is one of them. PyQt5 is cross-platform GUI
toolkit, a set of python bindings for Qt v5. One can develop an
interactive desktop application with so much ease because of the
tools and simplicity provided by this library.
In this article we will see how we can create a Paint application
using PyQt5. Our Paint application will consist of following
Features :

1. User can select different brush sizes


2. User can select different brush color
3. Saving of the canvas
4. Clearing the whole canvas at once

Steps for designing the widgets –


1. Create a window sets its geometry and title
2. Create menu bar
3. Inside menu bar add different menus, that are file menu, size
menu and color menu
4. Add save and clear action to the file menu

5. Add different brush sizes action to the brush size menu


6. Add different brush color action to the brush color menu

7. Create a white canvas and add it to the window


Back-end steps :
1. Create different variable : Drawing flag to check if currently
drawing or not and set it to False, brush size variable to set current
brush size, brush color to set current brush color and current
position variable to know position of cursor
2. Add action to the clear and save widget
3. Inside clear action fill the canvas with white color
4. Inside the save action save the canvas
5. Add actions(methods) to various brush sizes and color to set size
and color
6. Create paint event to draw white canvas on the screen
7. Create method to know when mouse left button is pressed inside
that method make drawing flag true and change the current
position
8. Create method for mouse movement, inside this method check if
drawing flag is true and button is still pressed then draw using
painter object and change the position according.
9. Create a method to know mouse button is released inside this
method make drawing flag to false.
Below is the implementation
Python3
# importing libraries

from PyQt5.QtWidgets import *

from PyQt5.QtGui import *

from PyQt5.QtCore import *

import sys

# window class

class Window(QMainWindow):

def __init__(self):

super().__init__()

# setting title

self.setWindowTitle("Paint with PyQt5")

# setting geometry to main window

self.setGeometry(100, 100, 800, 600)

# creating image object


self.image = QImage(self.size(), QImage.Format_RGB32)

# making image color to white

self.image.fill(Qt.white)

# variables

# drawing flag

self.drawing = False

# default brush size

self.brushSize = 2

# default color

self.brushColor = Qt.black

# QPoint object to tract the point

self.lastPoint = QPoint()

# creating menu bar

mainMenu = self.menuBar()

# creating file menu for save and clear action

fileMenu = mainMenu.addMenu("File")

# adding brush size to main menu

b_size = mainMenu.addMenu("Brush Size")


# adding brush color to ain menu

b_color = mainMenu.addMenu("Brush Color")

# creating save action

saveAction = QAction("Save", self)

# adding short cut for save action

saveAction.setShortcut("Ctrl + S")

# adding save to the file menu

fileMenu.addAction(saveAction)

# adding action to the save

saveAction.triggered.connect(self.save)

# creating clear action

clearAction = QAction("Clear", self)

# adding short cut to the clear action

clearAction.setShortcut("Ctrl + C")

# adding clear to the file menu

fileMenu.addAction(clearAction)

# adding action to the clear

clearAction.triggered.connect(self.clear)

# creating options for brush sizes

# creating action for selecting pixel of 4px

pix_4 = QAction("4px", self)

# adding this action to the brush size

b_size.addAction(pix_4)
# adding method to this

pix_4.triggered.connect(self.Pixel_4)

# similarly repeating above steps for different sizes

pix_7 = QAction("7px", self)

b_size.addAction(pix_7)

pix_7.triggered.connect(self.Pixel_7)

pix_9 = QAction("9px", self)

b_size.addAction(pix_9)

pix_9.triggered.connect(self.Pixel_9)

pix_12 = QAction("12px", self)

b_size.addAction(pix_12)

pix_12.triggered.connect(self.Pixel_12)

# creating options for brush color

# creating action for black color

black = QAction("Black", self)

# adding this action to the brush colors

b_color.addAction(black)

# adding methods to the black

black.triggered.connect(self.blackColor)

# similarly repeating above steps for different color


white = QAction("White", self)

b_color.addAction(white)

white.triggered.connect(self.whiteColor)

green = QAction("Green", self)

b_color.addAction(green)

green.triggered.connect(self.greenColor)

yellow = QAction("Yellow", self)

b_color.addAction(yellow)

yellow.triggered.connect(self.yellowColor)

red = QAction("Red", self)

b_color.addAction(red)

red.triggered.connect(self.redColor)

# method for checking mouse cicks

def mousePressEvent(self, event):

# if left mouse button is pressed

if event.button() == Qt.LeftButton:

# make drawing flag true

self.drawing = True

# make last point to the point of cursor


self.lastPoint = event.pos()

# method for tracking mouse activity

def mouseMoveEvent(self, event):

# checking if left button is pressed and drawing flag is true

if (event.buttons() & Qt.LeftButton) & self.drawing:

# creating painter object

painter = QPainter(self.image)

# set the pen of the painter

painter.setPen(QPen(self.brushColor, self.brushSize,

Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin))

# draw line from the last point of cursor to the current point

# this will draw only one step

painter.drawLine(self.lastPoint, event.pos())

# change the last point

self.lastPoint = event.pos()

# update

self.update()

# method for mouse left button release


def mouseReleaseEvent(self, event):

if event.button() == Qt.LeftButton:

# make drawing flag false

self.drawing = False

# paint event

def paintEvent(self, event):

# create a canvas

canvasPainter = QPainter(self)

# draw rectangle on the canvas

canvasPainter.drawImage(self.rect(), self.image, self.image.rect())

# method for saving canvas

def save(self):

filePath, _ = QFileDialog.getSaveFileName(self, "Save Image", "",

"PNG(*.png);;JPEG(*.jpg *.jpeg);;All Files(*.*) ")

if filePath == "":

return

self.image.save(filePath)

# method for clearing every thing on canvas


def clear(self):

# make the whole canvas white

self.image.fill(Qt.white)

# update

self.update()

# methods for changing pixel sizes

def Pixel_4(self):

self.brushSize = 4

def Pixel_7(self):

self.brushSize = 7

def Pixel_9(self):

self.brushSize = 9

def Pixel_12(self):

self.brushSize = 12

# methods for changing brush color

def blackColor(self):

self.brushColor = Qt.black
def whiteColor(self):

self.brushColor = Qt.white

def greenColor(self):

self.brushColor = Qt.green

def yellowColor(self):

self.brushColor = Qt.yellow

def redColor(self):

self.brushColor = Qt.red

# create pyqt5 app

App = QApplication(sys.argv)

# create the instance of our Window

window = Window()

# showing the window

window.show()

# start the app


sys.exit(App.exec())

# 4: Building QR Code Generator


Application using PyQt5
In this article we will see how we can make a QR code generator
application using PyQt5. A QR code is a type of matrix barcode
first designed in 1994 for the automotive industry in Japan. A
barcode is a machine-readable optical label that contains
information about the item to which it is attached. Below is how
the application will look like
In order to make this we will use the libraries given below
PyQt5 is cross-platform GUI toolkit, a set of python bindings for
Qt v5. One can develop an interactive desktop application with so
much ease because of the tools and simplicity provided by this
library. Below is the command to install the PyQt5

pip install PyQt5


qrcode :For generating a Quick Response code is a two-
dimensional pictographic code used for its fast readability and
comparatively large storage capacity. The code consists of black
modules arranged in a square pattern on a white background. The
information encoded can be made up of any kind of data (e.g.,
binary, alphanumeric, or Kanji symbols). Below is the command to
install the qrcode module

pip install qrcode

Implementation Steps :
1. Create a Image class which inherits qrcode base image
2. Inside the Image class, get the size from the border and width
and override the painter event and create a initial image and fill it
with white color
3. Create a main window class
4. Inside the window class create a label which will show the QR
code image
5. Create a line edit to receive the text from the user
6. Add label and line edit to the vertical layout and set layout to the
window
7. Add action to the line edit when entered is pressed
8. Inside the line edit action get the text of the line edit
9. Create a pixmap image of the line edit text and use Image class
as image_factory
10. Set the pixmap i.e QR code image to the label

Below is the implementation

Python3
# importing libraries

from PyQt5.QtWidgets import *

from PyQt5 import QtCore, QtGui

from PyQt5.QtGui import *

from PyQt5.QtCore import *

import qrcode

import sys

# Image class for QR code

class Image(qrcode.image.base.BaseImage):

# constructor

def __init__(self, border, width, box_size):

# assigning border

self.border = border
# assigning width

self.width = width

# assigning box size

self.box_size = box_size

# creating size

size = (width + border * 2) * box_size

# image

self._image = QImage(size, size, QImage.Format_RGB16)

# initial image as white

self._image.fill(Qt.white)

# pixmap method

def pixmap(self):

# returns image

return QPixmap.fromImage(self._image)

# drawrect method for drawing rectangle

def drawrect(self, row, col):


# creating painter object

painter = QPainter(self._image)

# drawing rectangle

painter.fillRect(

(col + self.border) * self.box_size,

(row + self.border) * self.box_size,

self.box_size, self.box_size,

QtCore.Qt.black)

# Main Window class

class Window(QMainWindow):

# constructor

def __init__(self):

QMainWindow.__init__(self)

# setting window title

self.setWindowTitle("QR Code")

# setting geometry

self.setGeometry(100, 100, 300, 300)

# creating a label to show the qr code

self.label = QLabel(self)
# creating a line edit to receive text

self.edit = QLineEdit(self)

# adding action when entered is pressed

self.edit.returnPressed.connect(self.handleTextEntered)

# setting font to the line edit

self.edit.setFont(QFont('Times', 9))

# setting alignment

self.edit.setAlignment(Qt.AlignCenter)

# creating a vertical layout

layout = QVBoxLayout(self)

# adding label to the layout

layout.addWidget(self.label)

# adding line edit to the layout

layout.addWidget(self.edit)

# creating a QWidget object

widget = QWidget()

# setting layout to the widget

widget.setLayout(layout)
# setting widget as central widget to the main window

self.setCentralWidget(widget)

# method called by the line edit

def handleTextEntered(self):

# get the text

text = self.edit.text()

# creating a pix map of qr code

qr_image = qrcode.make(text, image_factory = Image).pixmap()

# set image to the label

self.label.setPixmap(qr_image)

# create pyqt5 app

app = QApplication(sys.argv)

# create the instance of our Window

window = Window()

# showing window

window.show()
# start the app

sys.exit(app.exec_())

Output :

When user entered the text in the line edit and press enter key, QR
code will be displayed and window size will get adjusted according
to the size of QR code
# 5: Snake Game - PyQt5
In this article, we will see how we can design a simple snake game
using PyQt5. Snake is the common name for a video game concept
where the player maneuvers a line that grows in length, with the
line itself being a primary obstacle. The concept originated in the
1976 arcade game Blockade, and the ease of implementing Snake
has led to hundreds of versions (some of which have the word
snake or worm in the title) for many platforms.
Implementation steps :

1. Create a main window add status bar to it, to show the score
and create an object of board class and add it as central
widget.
2. Create a class named board which inherits the QFrame.
3. Inside the board class create a timer object which calls the
timer method after certain amount of time.
4. Inside the timer method call other action of the snake game
like movement, food eaten and if snake committed suicide.
5. Create a key press event method that check if arrow keys are
pressed and change the direction of the snake according to
it.
6. Create a paint event method that draws snake and the food.
7. Create move method to move the snake according to the
direction.
8. Create food eaten method that checks the snake current
position and position if food is eaten remove the current
food increment the snake length and drop a new food at
random location.
9. Create check suicide method that checks if snakehead
position is similar to the body position or not, if matches
stop the timer and show the message.
Below is the implementation:

Python3

# importing libraries

from PyQt5.QtCore import *

from PyQt5.QtWidgets import *

from PyQt5.QtGui import *

import random
import sys

# creating game window

class Window(QMainWindow):

def __init__(self):

super(Window, self).__init__()

# creating a board object

self.board = Board(self)

# creating a status bar to show result

self.statusbar = self.statusBar()

# adding border to the status bar

self.statusbar.setStyleSheet(& quot

border: 2px solid black

& quot

# calling showMessage method when signal received by board

self.board.msg2statusbar[str].connect(self.statusbar.showMessage)

# adding board as a central widget


self.setCentralWidget(self.board)

# setting title to the window

self.setWindowTitle('Snake game')

# setting geometry to the window

self.setGeometry(100, 100, 600, 400)

# starting the board object

self.board.start()

# showing the main window

self.show()

# creating a board class

# that inherits QFrame

class Board(QFrame):

# creating signal object

msg2statusbar = pyqtSignal(str)

# speed of the snake

# timer countdown time

SPEED = 80
# block width and height

WIDTHINBLOCKS = 60

HEIGHTINBLOCKS = 40

# constructor

def __init__(self, parent):

super(Board, self).__init__(parent)

# creating a timer

self.timer = QBasicTimer()

# snake

self.snake = [[5, 10], [5, 11]]

# current head x head

self.current_x_head = self.snake[0][0]

# current y head

self.current_y_head = self.snake[0][1]

# food list

self.food = []

# growing is false

self.grow_snake = False
# board list

self.board = []

# direction

self.direction = 1

# called drop food method

self.drop_food()

# setting focus

self.setFocusPolicy(Qt.StrongFocus)

# square width method

def square_width(self):

return self.contentsRect().width() / Board.WIDTHINBLOCKS

# square height

def square_height(self):

return self.contentsRect().height() / Board.HEIGHTINBLOCKS

# start method

def start(self):

# msg for status bar

# score = current len - 2


self.msg2statusbar.emit(str(len(self.snake) - 2))

# starting timer

self.timer.start(Board.SPEED, self)

# paint event

def paintEvent(self, event):

# creating painter object

painter = QPainter(self)

# getting rectangle

rect = self.contentsRect()

# board top

boardtop = rect.bottom() - Board.HEIGHTINBLOCKS * self.square_height()

# drawing snake

for pos in self.snake:

self.draw_square(painter, rect.left() + pos[0] * self.square_width(),

boardtop + pos[1] * self.square_height())

# drawing food

for pos in self.food:


self.draw_square(painter, rect.left() + pos[0] * self.square_width(),

boardtop + pos[1] * self.square_height())

# drawing square

def draw_square(self, painter, x, y):

# color

color = QColor(0x228B22)

# painting rectangle

painter.fillRect(x + 1, y + 1, self.square_width() - 2,

self.square_height() - 2, color)

# key press event

def keyPressEvent(self, event):

# getting key pressed

key = event.key()

# if left key pressed

if key == Qt.Key_Left:

# if direction is not right

if self.direction != 2:

# set direction to left


self.direction = 1

# if right key is pressed

elif key == Qt.Key_Right:

# if direction is not left

if self.direction != 1:

# set direction to right

self.direction = 2

# if down key is pressed

elif key == Qt.Key_Down:

# if direction is not up

if self.direction != 4:

# set direction to down

self.direction = 3

# if up key is pressed

elif key == Qt.Key_Up:

# if direction is not down

if self.direction != 3:

# set direction to up

self.direction = 4

# method to move the snake


def move_snake(self):

# if direction is left change its position

if self.direction == 1:

self.current_x_head, self.current_y_head = self.current_x_head - 1,


self.current_y_head

# if it goes beyond left wall

if self.current_x_head & lt

0:

self.current_x_head = Board.WIDTHINBLOCKS - 1

# if direction is right change its position

if self.direction == 2:

self.current_x_head, self.current_y_head = self.current_x_head + 1,


self.current_y_head

# if it goes beyond right wall

if self.current_x_head == Board.WIDTHINBLOCKS:

self.current_x_head = 0

# if direction is down change its position

if self.direction == 3:

self.current_x_head, self.current_y_head = self.current_x_head,


self.current_y_head + 1
# if it goes beyond down wall

if self.current_y_head == Board.HEIGHTINBLOCKS:

self.current_y_head = 0

# if direction is up change its position

if self.direction == 4:

self.current_x_head, self.current_y_head = self.current_x_head,


self.current_y_head - 1

# if it goes beyond up wall

if self.current_y_head & lt

0:

self.current_y_head = Board.HEIGHTINBLOCKS

# changing head position

head = [self.current_x_head, self.current_y_head]

# inset head in snake list

self.snake.insert(0, head)

# if snake grow is False

if not self.grow_snake:

# pop the last element

self.snake.pop()

else:
# show msg in status bar

self.msg2statusbar.emit(str(len(self.snake)-2))

# make grow_snake to false

self.grow_snake = False

# time event method

def timerEvent(self, event):

# checking timer id

if event.timerId() == self.timer.timerId():

# call move snake method

self.move_snake()

# call food collision method

self.is_food_collision()

# call is suicide method

self.is_suicide()

# update the window

self.update()

# method to check if snake collides itself

def is_suicide(self):

# traversing the snake

for i in range(1, len(self.snake)):

# if collision found
if self.snake[i] == self.snake[0]:

# show game ended msg in status bar

self.msg2statusbar.emit(str(& quot

Game Ended & quot

))

# making background color black

self.setStyleSheet(& quot

background-color: black

& quot

# stopping the timer

self.timer.stop()

# updating the window

self.update()

# method to check if the food cis collied

def is_food_collision(self):

# traversing the position of the food

for pos in self.food:

# if food position is similar of snake position

if pos == self.snake[0]:

# remove the food

self.food.remove(pos)

# call drop food method

self.drop_food()
# grow the snake

self.grow_snake = True

# method to drop food on screen

def drop_food(self):

# creating random co-ordinates

x = random.randint(3, 58)

y = random.randint(3, 38)

# traversing if snake position is not equal to the

# food position so that food do not drop on snake

for pos in self.snake:

# if position matches

if pos == [x, y]:

# call drop food method again

self.drop_food()

# append food location

self.food.append([x, y])

# main method

if __name__ == '__main__':

app = QApplication([])
window = Window()

sys.exit(app.exec_())

Code Explanation:
1. The code starts by creating a new class, Window.
2. This class will be the main window for our application.
3. Next, the __init__() method is called.
4. In this method, we set the title of the window and configure
its geometry.
5. We also call UiComponents(), which is a special method
that will show all of our widgets in the window.
6. Now let’s take a look at what happens when we run this
code.
7. First, we create an instance of Window and set its title to
“Python”.
8. Then we configure the window’s geometry by setting its size
to 100 x 100 pixels and its position to 320 x 400 pixels
onscreen (see Figure 1-1).
9. Figure 1-1: The Python Window with Its Geometry
Configured Next, we call UiComponents().
10.
This method will show all of our widgets in the window
(see Figure 1-2).
11.
Window object Figure 1-2: The Python Window With All
Its Widgets Shown In this example, there are only two
widgets in our window—the text box and the button.
12.
However, you can add as many widgets
13.
The code creates a new window and sets its title to
“Python”.
14.
It then sets the window’s geometry to (100, 100, 320,
400).
15.
Finally, it calls the UiComponents() method on the
window object.
16.
The UiComponents() method is responsible for displaying
all of the widgets in the window.
17.
The code first shows all of the widgets by calling show().
18.
After showing all of the widgets, the code calls a method
called updateWidget().
19.
This method is responsible for updating each widget in the
window.
20.
The code starts by creating a QLabel object and setting its
geometry to 20, 10, and 280 pixels wide by 60 pixels high.
21.
The label’s font is then set to Times New Roman with
bold and italic settings enabled, and underline enabled.
22.
Finally, the head’s alignment is set to Qt.AlignCenter.
23.
Next, the code creates a choice variable and sets it to 0.
24.
The choice variable will store the user’s selection between
rock (0) and paper (1).
25.
The next line of code creates a head label object and sets
its geometry to 20, 10, 280 pixels wide by 60 pixels high.
26.
The label’s font is then set to Times New Roman with
bold and italic settings enabled, as well as underline
disabled.
27.
Finally, the head’s alignment is set to
Qt.AlignLeftJustified.
28.
Next , we create two buttons using QPushButton objects .
29.
One button will be used for selecting rock or paper , while
the other will be used for cancelling out of the game .
30.
We first create a QPushButton object named “rock” .
31.
This button will be used for selecting whether or not the
player wants to play with rocks .
32.
The code creates a QLabel object and sets its geometry to
20 x 10 pixels, with the top-left corner at (280, 60) pixels.
33.
The font is then set to Times New Roman font with the
bold, italic, and underline properties set to True.
34.
Finally, the head’s alignment is set to Qt.AlignCenter.
35.
The code starts by creating a new QGraphicsItem, which
is the head of the user interface.
36.
The head object has a GraphicsEffect property that can be
set to one of several color effects.
37.
In this example, we use the QGraphicsColorizeEffect class
to change the color of the head object to dark cyan.
38.
Next, we create a new QLabel object and set its geometry
to 150 x 110 pixels in size, with a width of 30 pixels and a
height of 50 pixels.
39.
We also set its font properties to underline (false) and
italic (false), so that it will not display any text.
40.
Finally, we create another QLabel object called user and
set its geometry to 50 x 100 pixels in size, with a width of
70 pixels and a height of 70 pixels.
41.
Now let’s take a look at some code that uses these objects:
# setting colors self.head.setGraphicsEffect(Qt.darkCyan) #
creating vs label self.vs = QLabel(“vs”, self) # setting
geometry self.vs.setGeometry(150, 110, 30, 50)
42.
The code will create a QGraphicsItem object called head,
and set the graphics effect to colorize.
43.
The head will also have a QLabel object created and
assigned as its parent.
44.
The label will be given a geometry of 150 x 110 pixels,
with a width of 30 pixels and a height of 50 pixels.
45.
Next, the font for the label will be set to italic and
underline disabled.
46.
Finally, the user QLabel object will be created with the
same dimensions as head.
47.
The code starts by creating a user interface.
48.
The user interface consists of three labels, a computer
choice label, and three push buttons.
49.
The first button, the rock button, is set to have a geometry
of 30 x 270 pixels with an 80 pixel border and a 35 pixel
center point.
50.
The second button, the paper button, is set to have a
geometry of 120 x 270 pixels with an 80 pixel border and a
35 pixel center point.
51.
The third button, the scissors button, is set to have a
geometry of 210 x 270 pixels with an 80 pixel border and a
35 pixel center point.
52.
Next, the code sets up actions for each of the buttons.
53.
For the rock button, the code connects it to an action that
prints “Rock” onscreen when it is clicked.
54.
For the paper button, the code connects it to an action that
prints “Paper” onscreen when it is clicked.
55.
For the scissors button, the code connects it to an action
that prints “Scissors” onscreen when it is clicked.
56.
The code creates a user interface with three push buttons.
57.
The first push button, Rock, is configured to have the
following geometry: 30 x 270 x 80 pixels.
58.
The second push button, Paper, is configured to have the
following geometry: 120 x 270 x 80 pixels.
59.
The third push button, Scissor, is configured to have the
following geometry: 210 x 270 x 80 pixels.
60.
Each of the buttons has an action associated with it.
61.
The rock button’s action is connected to the rock_action
function and will be executed when it is clicked.
62.
The paper button’s action is connected to the paper_action
function and will be executed when it is clicked.
63.
The scissor button’s action is connected to the sc
64.
The code starts by creating a QPushButton object named
game_reset.
65.
The button has the following properties: name:
“game_reset” label: “Reset” icon:
“ui/images/pushbutton.png” Next, the code sets the
geometry of the button using setGeometry().
66.
The coordinates are (100, 320, 120, 50).
67.
The size of the button is also specified (it will be 100×32
pixels).
68.
Finally, a color effect is added to the button with
setGraphicsEffect().
69.
This effect uses Qt’s red color as its base color.
70.
The next step is to create an action handler for the
game_reset button.
71.
This handler will be called when someone clicks on it.
72.
The code creates a QTimer object and attaches an action to
it called timeout().
73.
This action will cause the timer to run for 1000
milliseconds (1 second).
74.
After that time has elapsed, the showTime() function will
be executed.
75.
This function simply displays a message onscreen saying
“timer started.”
76.
The code creates a QPushButton named game_reset and
sets its geometry to 100 x 320 pixels, with a width of 120
pixels and a height of 50 pixels.
77.
It also sets the button’s color to red.
78.
Next, the code creates a QGraphicsColorizeEffect object
and sets its color to Qt.red.
79.
Finally, the code adds an action to the game_reset button
called clicked, which connects it to the self.reset_action
function.
80.
This function will be executed when the user clicks on the
game_reset button.
81.
The last part of this code is responsible for creating a timer
object and adding an action to it called timeout that connects
it to the self.showTime function.
82.
This function will
83.
The code starts by initializing some variables.
84.
The first variable is self.counter, which will keep track of
the number of times the rock, paper, and scissor buttons
have been clicked.
85.
Next, the code sets up three buttons (rock, paper, and
scissor) and defines their respective actions.
86.
When a user clicks on the rock button, the code sets
self.choice to 1 and sets the border image for the user’s label
to rock.png.
87.
When a user clicks on the paper button, the code sets
self.choice to 2 and sets the border image for the user’s label
to Paper.png.
88.
Finally, when a user clicks on the scissor button, the code
sets self.choice to 3 and sets the border image
fortheuser’slabeltoScissor.png .
89.
Next comes some logic that checks who won each match
between users Rock vs Paper , Rock vs Scissor , and Paper
vs Scissor .
90.
If one of these matches has already been made (by either
player clicking on one of those buttons), then nothing
happens; no new images are displayed or changed in any
way onscreen because there is no need to do so since both
players
91.
The code first sets up some variables to store information
about the user’s choices.
92.
These variables are used later on in the code when it
comes time to check who won the match.
93.
Next, the code checks to see if any of the buttons have
been clicked.
94.
If one of the buttons has been clicked, then the appropriate
action is taken.
95.
If no button has been clicked, then the code sets up three
buttons and determines which one the user will choose by
checking their choice variable.
96.
Once this decision is made, the appropriate rock image,
paper image, or scissor image is set as the user’s label and
counter value is decreased by 1.

# 6: Age Calculator using PyQt

In this article we will see how we can create an age calculator using
PyQt5.
PyQt5 is cross-platform GUI toolkit, a set of python bindings for
Qt v5. One can develop an interactive desktop application with so
much ease because of the tools and simplicity provided by this
library. It has to be installed using command given below
pip install PyQt5

Below is how age calculator will look like


GUI Implementation Steps :
1. Create a head label for the title of the game, set its properties
2. Create a date of birth label, below this label create QDateEdit
object to receive the date and set their properties
3. Create a given date label, below this label create QDateEdit
object to receive the new date and set their properties
4. Create a push button which when pressed date is calculated
5. Create result label to show the result i.e calculated age
Back-End implementation Steps :
1. Add action to the first QDateEdit when date is changed
2. Inside the first date edit action get the date of second date edit
and set this date as maximum date of the first date edit
3. Add action to the second date edit when date is changed
4. Inside the second date edit action get the date of the first date
edit and set this date as minimum date of the second date edit
5. Set different date edits such that first date should be less than
second date
6. Add action to the push button
7. Inside the push button action, get the dates from both the date
edits and calculate the difference and show the difference to the
screen with the help of result label
Below is the implementation

# importing libraries

from PyQt5.QtWidgets import *

from PyQt5 import QtCore, QtGui

from PyQt5.QtGui import *

from PyQt5.QtCore import *

import sys

class Window(QMainWindow):

def __init__(self):

super().__init__()

# setting title

self.setWindowTitle("Age calculator")
# setting geometry

self.setGeometry(100, 100, 500, 400)

# calling method

self.UiComponents()

# showing all the widgets

self.show()

# method for components

def UiComponents(self):

# creating head label

head = QLabel("Age Calculator", self)

# setting geometry to the head

head.setGeometry(100, 10, 300, 60)

# font

font = QFont('Times', 14)

font.setBold(True)

font.setItalic(True)

font.setUnderline(True)

# setting font to the head

head.setFont(font)
# setting alignment of the head

head.setAlignment(Qt.AlignCenter)

head.setStyleSheet("color : green;")

# D.O.B label

dob = QLabel("Date of Birth", self)

# setting geometry

dob.setGeometry(0, 80, 250, 50)

# setting alignment and font

dob.setAlignment(Qt.AlignCenter)

dob.setFont(QFont('Times', 10))

# given date label

given = QLabel("Given Date", self)

# setting geometry

given.setGeometry(300, 80, 250, 50)

# setting alignment and font

given.setAlignment(Qt.AlignCenter)

given.setFont(QFont('Times', 10))

# creating a QDateEdit to get the d.o.b

self.first = QDateEdit(self)
# setting geometry

self.first.setGeometry(25, 130, 200, 50)

# setting font and alignment

self.first.setAlignment(Qt.AlignCenter)

self.first.setFont(QFont('Arial', 9))

# adding action to the first

# when date get change

self.first.dateChanged.connect(self.first_action)

# creating a QDateEdit to get the given date

self.second = QDateEdit(self)

# setting geometry

self.second.setGeometry(275, 130, 200, 50)

# setting font and alignment

self.second.setAlignment(Qt.AlignCenter)

self.second.setFont(QFont('Arial', 9))

# adding action to the second

# when date get change

self.second.dateChanged.connect(self.second_action)

# create a push button for calculate

calculate = QPushButton("Calculate", self)


# setting geometry to the push button

calculate.setGeometry(200, 210, 100, 40)

# setting color effect to the push button

color = QGraphicsColorizeEffect()

color.setColor(Qt.darkGreen)

calculate.setGraphicsEffect(color)

# adding action to the calculate button

calculate.clicked.connect(self.find_age)

# creating a result label to show the ans

self.result = QLabel(self)

# setting geometry

self.result.setGeometry(50, 280, 400, 80)

# setting style sheet and the font

self.result.setAlignment(Qt.AlignCenter)

self.result.setFont(QFont('Times', 12))

# setting stylesheet

self.result.setStyleSheet("QLabel"

"{"

"border : 2px solid black;"

"background : lightgrey;"

"}")
# making label multi line

self.result.setWordWrap(True)

# set dates to the first and second

self.first.setDate(QDate(2000, 1, 1))

self.second.setDate(QDate(2020, 1, 1))

# method called by the first date edit

def first_action(self):

# get the second date

date = self.second.date()

# set the maximum date in first

self.first.setMaximumDate(date)

# method called by the first date edit

def second_action(self):

# get the first date

date = self.first.date()

# set the maximum date in first

self.second.setMinimumDate(date)
# method called by the push button

def find_age(self):

# get the first age

get_Qdate1 = self.first.date()

birth_year = get_Qdate1.year()

birth_month = get_Qdate1.month()

birth_day = get_Qdate1.day()

# get the second age

get_Qdate2 = self.second.date()

given_year = get_Qdate2.year()

given_month = get_Qdate2.month()

given_day = get_Qdate2.day()

# if birth date is greater then given birth_month

# then donot count this month and add 30 to the date so

# as to subtract the date and get the remaining days

month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]

if (birth_day > given_day):

given_month = given_month - 1
given_day = given_day + month[birth_month - 1]

# if birth month exceeds given month, then

# donot count this year and add 12 to the

# month so that we can subtract and find out

# the difference

if (birth_month > given_month):

given_year = given_year - 1

given_month = given_month + 12

# calculate day, month, year

calculated_day = given_day - birth_day

calculated_month = given_month - birth_month

calculated_year = given_year - birth_year

# setting text to the result

self.result.setText(str(calculated_day) + " Day(s), " + str(calculated_month)

+ " Month(s), " + str(calculated_year) + " Year(s)")

# create pyqt5 app

App = QApplication(sys.argv)
# create the instance of our Window

window = Window()

# start the app

sys.exit(App.exec())

# 7: Number Guessing Game - PyQt5

In this article we will see how we can create a number guessing


name using PyQt5. The Number guessing game is all about
guessing the number randomly chosen by the computer in the given
number of chances. Below is how game will look like
GUI implementation steps 1. Create a head label to show the game
name, set its alignment font and color 2. Create a info label that
gives all the information and set its style sheet 3. Create a spin box
to change the guessed number 4. Create a push button to check the
guess 5. Create a start and reset buttons and add color effect to
them Back end implementation steps 1. Create a variable number
that will store the random number 2. Add action to the start button
3. Inside the start button action get the random number from 1 to
20 using random method 4. Set the text to the info label and change
its color to grey 5. Add action to the check button 6. Inside the
check button action, get the spin box value and compare it with the
random number 7. If numbers are equal change info label color to
green and set text as “correct” 8. Else check if smaller then say
number is smaller guess again similarly do if number is bigger 9.
Add action to the reset button 10. Inside the reset action set
welcome text to info label and set its color to grey
Below is the implementation

Python3

# importing libraries

from PyQt5.QtWidgets import *

from PyQt5 import QtCore, QtGui

from PyQt5.QtGui import *

from PyQt5.QtCore import *

import random

import sys

class Window(QMainWindow):

def __init__(self):

super().__init__()

# setting title

self.setWindowTitle("Python ")

# setting geometry

self.setGeometry(100, 100, 340, 350)


# calling method

self.UiComponents()

# showing all the widgets

self.show()

# number

self.number = 0

# method for components

def UiComponents(self):

# creating head label

head = QLabel("Number Guessing Game", self)

# setting geometry to the head

head.setGeometry(20, 10, 300, 60)

# font

font = QFont('Times', 14)

font.setBold(True)

font.setItalic(True)

font.setUnderline(True)

# setting font to the head

head.setFont(font)
# setting alignment of the head

head.setAlignment(Qt.AlignCenter)

# setting color effect to the head

color = QGraphicsColorizeEffect(self)

color.setColor(Qt.darkCyan)

head.setGraphicsEffect(color)

# creating a label that will give the info

self.info = QLabel("Welcome", self)

# setting geometry to the info label

self.info.setGeometry(40, 85, 260, 60)

# making the info label multi line

self.info.setWordWrap(True)

# setting font and alignment

self.info.setFont(QFont('Times', 13))

self.info.setAlignment(Qt.AlignCenter)

# setting style sheet

self.info.setStyleSheet("QLabel"

"{"

"border : 2px solid black;"

"background : lightgrey;"

"}")
# creating a spin box to set the number

self.spin = QSpinBox(self)

# setting range to the spin box

self.spin.setRange(1, 20)

# setting geometry to the spin box

self.spin.setGeometry(120, 170, 100, 60)

# setting alignment and font

self.spin.setAlignment(Qt.AlignCenter)

self.spin.setFont(QFont('Times', 15))

# creating a push button to check the guess number

check = QPushButton("Check", self)

# setting geometry to the push button

check.setGeometry(130, 235, 80, 30)

# adding action to the check button

check.clicked.connect(self.check_action)

# creating a start button

start = QPushButton("Start", self)

start.setGeometry(65, 280, 100, 40)

# reset button to reset the game


reset_game = QPushButton("Reset", self)

# setting geometry to the push button

reset_game.setGeometry(175, 280, 100, 40)

# setting color effect

color_red = QGraphicsColorizeEffect()

color_red.setColor(Qt.red)

reset_game.setGraphicsEffect(color_red)

color_green = QGraphicsColorizeEffect()

color_green.setColor(Qt.darkBlue)

start.setGraphicsEffect(color_green)

# adding action to the button

start.clicked.connect(self.start_action)

reset_game.clicked.connect(self.reset_action)

def start_action(self):

# making label green

self.info.setStyleSheet("QLabel"

"{"

"border : 2px solid black;"

"background : lightgrey;"
"}")

# creating random number

self.number = random.randint(1, 20)

# setting text to the info label

self.info.setText("Try to guess number between 1 to 20")

def check_action(self):

# get the spin box number

user_number = self.spin.value()

# check the value

if user_number == self.number:

# setting text to the info label

self.info.setText("Correct Guess")

# making label green

self.info.setStyleSheet("QLabel"

"{"

"border : 2px solid black;"

"background : lightgreen;"

"}")
elif user_number < self.number:

# giving hint

self.info.setText("Your number is smaller")

else:

# giving hint

self.info.setText("Your number is bigger")

def reset_action(self):

# making label green

self.info.setStyleSheet("QLabel"

"{"

"border : 2px solid black;"

"background : lightgrey;"

"}")

# setting text to the info label

self.info.setText("Welcome")

# create pyqt5 app


App = QApplication(sys.argv)

# create the instance of our Window

window = Window()

# start the app

sys.exit(App.exec())

# 8: Jumble Word Game - PyQt5


In this article we will see how we can create a jumble word game
using PyQt5. Jumbled word game : Jumbled word is given to
player, player has to rearrange the characters of the word to make a
correct meaningful word. Below is how game will look like
GUI implementation steps :
1. Create a heading label that display the game name
2. Create label that shows the jumbled word
3. A line edit widget that get the text
4. A push button that check the input text which is beside the line
edit
5. Create a result label that tells if answer is correct or not and
change its color
6. Two push button to start and reset the game

Back end implementation steps :


1. Create a list of words
2. Add action to the check button
3. Inside the action of check push button get the input text and
compare it with the input word
4. If word matches show result as correct and set color to green
else set color to red and say wrong
5. Add action to the start button
5. Inside the start button action get the current word from the list
using random function
6. Create a jumble word from the current word and set it to the
jumble label
7. Remove the text of the result label and set color to yellow
8. Add action to the reset button
9. Inside the reset button action set the current word to blank
10. Remove text from all labels and set their color back to original
one
Below is the implementation
Python3
# importing libraries

from PyQt5.QtWidgets import *

from PyQt5 import QtCore, QtGui

from PyQt5.QtGui import *

from PyQt5.QtCore import *

import random

import sys

class Window(QMainWindow):
def __init__(self):

super().__init__()

# setting title

self.setWindowTitle("Python ")

# setting geometry

self.setGeometry(100, 100, 320, 350)

# calling method

self.UiComponents()

# showing all the widgets

self.show()

# words

self.words = ['red', 'cold', 'hot', 'geeks', 'rain',

'black', 'snow', 'hills', 'code']

# current word

self.current_text = ""

# method for components

def UiComponents(self):

# creating head label


head = QLabel("Jumbled Word Game", self)

# setting geometry to the head

head.setGeometry(20, 10, 280, 60)

# font

font = QFont('Times', 15)

font.setBold(True)

font.setItalic(True)

font.setUnderline(True)

# setting font to the head

head.setFont(font)

# setting alignment of the head

head.setAlignment(Qt.AlignCenter)

# setting color effect to the head

color = QGraphicsColorizeEffect(self)

color.setColor(Qt.darkCyan)

head.setGraphicsEffect(color)

# creating label to show the jumbled word

self.j_word = QLabel(self)

# setting geometry
self.j_word.setGeometry(30, 80, 260, 50)

# setting style sheet

self.j_word.setStyleSheet("border : 2px solid black; background : white;")

# setting font

self.j_word.setFont(QFont('Times', 12))

# setting alignment

self.j_word.setAlignment(Qt.AlignCenter)

# creating a line edit widget to get the text

self.input = QLineEdit(self)

# setting geometry

self.input.setGeometry(20, 150, 200, 40)

# setting alignment

self.input.setAlignment(Qt.AlignCenter)

# creating push button to check the input

self.check = QPushButton("Check", self)

# setting geometry

self.check.setGeometry(230, 155, 80, 30)


# adding action to the check button

self.check.clicked.connect(self.check_action)

# result label

self.result = QLabel(self)

# setting geometry

self.result.setGeometry(40, 210, 240, 50)

# setting font

self.result.setFont(QFont('Times', 13))

# setting alignment

self.result.setAlignment(Qt.AlignCenter)

# setting style sheet

self.result.setStyleSheet("border : 2px solid black; background : yellow;")

# creating push buttons to start and reset the game

start = QPushButton("Start", self)

reset = QPushButton("Reset", self)

# setting geometry to both the button

start.setGeometry(15, 290, 140, 40)

reset.setGeometry(165, 290, 140, 40)


# adding action to both the buttons

start.clicked.connect(self.start_action)

reset.clicked.connect(self.reset_action)

def check_action(self):

# getting text from the line edit

text = self.input.text()

# checking if text is similar to the current text

if text == self.current_text:

self.result.setText("Correct Answer")

# making result color green

self.result.setStyleSheet("background : lightgreen;")

else:

self.result.setText("Wrong Answer")

# making result color red

self.result.setStyleSheet("background : red;")

def start_action(self):
# selecting one word

self.current_text = random.choice(self.words)

# sample() method shuffling the characters of the word

random_word = random.sample(self.current_text, len(self.current_text))

# join() method join the elements

# of the iterator(e.g. list) with particular character .

jumbled = ''.join(random_word)

# setting text to the jumbled word

self.j_word.setText(jumbled)

# setting result text to blank

self.result.setText("")

# making result label color yellow

self.result.setStyleSheet("border : 2px solid black; background : yellow;")

# setting text of input to blank

self.input.setText("")

def reset_action(self):

# setting current text blank


self.current_text = ""

# setting text of input to blank

self.input.setText("")

# clear the text of all the labels

self.j_word.setText("")

self.result.setText("")

# making result label color yellow

self.result.setStyleSheet("border : 2px solid black; background : yellow;")

# create pyqt5 app

App = QApplication(sys.argv)

# create the instance of our Window

window = Window()

# start the app

sys.exit(App.exec())
Conclusion

This book is dedicated to the readers who take time to write me


each day. Every morning I’m greeted by various emails — some
with requests, a few with complaints, and then there are the very
few that just say thank you. All these emails encourage and
challenge me as an author — to better both my books and myself.
Thank you!

You might also like