Python GUI Applications Using PyQt5 _ the Hands-On Guide to Build Apps With Python
Python GUI Applications Using PyQt5 _ the Hands-On Guide to Build Apps With Python
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
About Python
# 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’.
# 1: Opening a window
Example
import sys
from PyQt5.QtWidgets import QApplication, QWidget
class MyApp(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
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 .
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.
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.
Results
# 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):
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.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
# 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')
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.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 참
고)
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):
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
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.
Displaying date
The QDate class provides date-related features.
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.
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
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.
datetime = QDateTime.currentDateTime()
print(datetime.toString())
currentDateTime() method restores current date and time.
toString() method restores date and time as as string.
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.
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.
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:
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):
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
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 )
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
# 1: QPushButton
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.
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):
btn2 = QPushButton(self)
btn2.setText('Button&2')
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):
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.
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.
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):
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.
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.
메서드 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):
rbtn2 = QRadioButton(self)
rbtn2.move(50, 70)
rbtn2.setText('Second Button')
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):
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()
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.
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)).
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()
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.
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()
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)
self.validator_le.clear()
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)
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;#')
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.
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.timer = QBasicTimer()
self.step = 0
self.setWindowTitle('QProgressBar')
self.setGeometry(300, 300, 300, 200)
self.show()
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.
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
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.dial = QDial(self)
self.dial.move(30, 50)
self.dial.setRange(0, 50)
self.slider.valueChanged.connect(self.dial.setValue)
self.dial.valueChanged.connect(self.slider.setValue)
btn.clicked.connect(self.button_clicked)
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)
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.
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
# 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)
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.
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):
vbox1 = QVBoxLayout()
vbox1.addWidget(combo)
lan_group.setLayout(vbox1)
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):
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):
...
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):
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’.
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.
Results
Figure 5-12. Use QPixmap to display image.
# 15: QCalendarWidget
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()
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.
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.
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
# 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.
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.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()
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.le = QLineEdit(self)
self.le.move(120, 35)
self.setWindowTitle('Input dialog')
self.setGeometry(300, 300, 300, 200)
self.show()
def showDialog(self):
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.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):
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()
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):
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()
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.
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
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)
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
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)
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.
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()
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.
class MyApp(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
x=0
y=0
x = e.x()
y = e.y()
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.
x = e.x()
y = e.y()
Results
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.
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
Python3
import os
import sys
class MainWindow(QMainWindow):
# constructor
# creating a QWebEngineView
self.browser = QWebEngineView()
self.browser.setUrl(QUrl("http://google.com"))
self.browser.urlChanged.connect(self.update_urlbar)
self.browser.loadFinished.connect(self.update_title)
# set this browser as central widget or main window
self.setCentralWidget(self.browser)
self.status = QStatusBar()
self.setStatusBar(self.status)
navtb = QToolBar("Navigation")
self.addToolBar(navtb)
back_btn.triggered.connect(self.browser.back)
next_btn.triggered.connect(self.browser.forward)
navtb.addAction(next_btn)
reload_btn.setStatusTip("Reload page")
reload_btn.triggered.connect(self.browser.reload)
navtb.addAction(reload_btn)
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()
self.urlbar = QLineEdit()
self.urlbar.returnPressed.connect(self.navigate_to_url)
navtb.addWidget(self.urlbar)
stop_btn.triggered.connect(self.browser.stop)
navtb.addAction(stop_btn)
self.show()
def update_title(self):
title = self.browser.page().title()
def navigate_home(self):
self.browser.setUrl(QUrl("http://www.google.com"))
def navigate_to_url(self):
q = QUrl(self.urlbar.text())
if q.scheme() == "":
q.setScheme("http")
self.browser.setUrl(q)
self.urlbar.setText(q.toString())
self.urlbar.setCursorPosition(0)
app = QApplication(sys.argv)
app.setApplicationName("Geek Browser")
window = MainWindow()
# loop
app.exec_()
Python3
# importing libraries
import sys
class Window(QMainWindow):
def __init__(self):
super().__init__()
# setting title
self.setWindowTitle("Python ")
# setting geometry
# calling method
self.UiComponents()
self.show()
def UiComponents(self):
# variables
# count variable
self.count = 0
# start flag
self.start = False
button.clicked.connect(self.get_seconds)
self.label.setFont(QFont('Times', 15))
self.label.setAlignment(Qt.AlignCenter)
start_button.clicked.connect(self.start_action)
pause_button.clicked.connect(self.pause_action)
reset_button.clicked.connect(self.reset_action)
timer = QTimer(self)
# adding action to timer
timer.timeout.connect(self.showTime)
timer.start(100)
def showTime(self):
if self.start:
self.count -= 1
# timer is completed
if self.count == 0:
self.start = False
if self.start:
# showing text
self.label.setText(text)
def get_seconds(self):
self.start = False
# if flag is true
if done:
self.count = second * 10
self.label.setText(str(second))
def start_action(self):
# count = 0
if self.count == 0:
self.start = False
def pause_action(self):
self.start = False
def reset_action(self):
self.start = False
self.count = 0
self.label.setText("//TIMER//")
window = Window()
sys.exit(App.exec())
import sys
# window class
class Window(QMainWindow):
def __init__(self):
super().__init__()
# setting title
self.image.fill(Qt.white)
# variables
# drawing flag
self.drawing = False
self.brushSize = 2
# default color
self.brushColor = Qt.black
self.lastPoint = QPoint()
mainMenu = self.menuBar()
fileMenu = mainMenu.addMenu("File")
saveAction.setShortcut("Ctrl + S")
fileMenu.addAction(saveAction)
saveAction.triggered.connect(self.save)
clearAction.setShortcut("Ctrl + C")
fileMenu.addAction(clearAction)
clearAction.triggered.connect(self.clear)
b_size.addAction(pix_4)
# adding method to this
pix_4.triggered.connect(self.Pixel_4)
b_size.addAction(pix_7)
pix_7.triggered.connect(self.Pixel_7)
b_size.addAction(pix_9)
pix_9.triggered.connect(self.Pixel_9)
b_size.addAction(pix_12)
pix_12.triggered.connect(self.Pixel_12)
b_color.addAction(black)
black.triggered.connect(self.blackColor)
b_color.addAction(white)
white.triggered.connect(self.whiteColor)
b_color.addAction(green)
green.triggered.connect(self.greenColor)
b_color.addAction(yellow)
yellow.triggered.connect(self.yellowColor)
b_color.addAction(red)
red.triggered.connect(self.redColor)
if event.button() == Qt.LeftButton:
self.drawing = True
painter = QPainter(self.image)
painter.setPen(QPen(self.brushColor, self.brushSize,
# draw line from the last point of cursor to the current point
painter.drawLine(self.lastPoint, event.pos())
self.lastPoint = event.pos()
# update
self.update()
if event.button() == Qt.LeftButton:
self.drawing = False
# paint event
# create a canvas
canvasPainter = QPainter(self)
def save(self):
if filePath == "":
return
self.image.save(filePath)
self.image.fill(Qt.white)
# update
self.update()
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
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
App = QApplication(sys.argv)
window = Window()
window.show()
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
Python3
# importing libraries
import qrcode
import sys
class Image(qrcode.image.base.BaseImage):
# constructor
# assigning border
self.border = border
# assigning width
self.width = width
self.box_size = box_size
# creating size
# image
self._image.fill(Qt.white)
# pixmap method
def pixmap(self):
# returns image
return QPixmap.fromImage(self._image)
painter = QPainter(self._image)
# drawing rectangle
painter.fillRect(
self.box_size, self.box_size,
QtCore.Qt.black)
class Window(QMainWindow):
# constructor
def __init__(self):
QMainWindow.__init__(self)
self.setWindowTitle("QR Code")
# setting geometry
self.label = QLabel(self)
# creating a line edit to receive text
self.edit = QLineEdit(self)
self.edit.returnPressed.connect(self.handleTextEntered)
self.edit.setFont(QFont('Times', 9))
# setting alignment
self.edit.setAlignment(Qt.AlignCenter)
layout = QVBoxLayout(self)
layout.addWidget(self.label)
layout.addWidget(self.edit)
widget = QWidget()
widget.setLayout(layout)
# setting widget as central widget to the main window
self.setCentralWidget(widget)
def handleTextEntered(self):
text = self.edit.text()
self.label.setPixmap(qr_image)
app = QApplication(sys.argv)
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
import random
import sys
class Window(QMainWindow):
def __init__(self):
super(Window, self).__init__()
self.board = Board(self)
self.statusbar = self.statusBar()
self.statusbar.setStyleSheet(& quot
& quot
self.board.msg2statusbar[str].connect(self.statusbar.showMessage)
self.setWindowTitle('Snake game')
self.board.start()
self.show()
class Board(QFrame):
msg2statusbar = pyqtSignal(str)
SPEED = 80
# block width and height
WIDTHINBLOCKS = 60
HEIGHTINBLOCKS = 40
# constructor
super(Board, self).__init__(parent)
# creating a timer
self.timer = QBasicTimer()
# snake
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
self.drop_food()
# setting focus
self.setFocusPolicy(Qt.StrongFocus)
def square_width(self):
# square height
def square_height(self):
# start method
def start(self):
# starting timer
self.timer.start(Board.SPEED, self)
# paint event
painter = QPainter(self)
# getting rectangle
rect = self.contentsRect()
# board top
# drawing snake
# drawing food
# drawing square
# color
color = QColor(0x228B22)
# painting rectangle
painter.fillRect(x + 1, y + 1, self.square_width() - 2,
self.square_height() - 2, color)
key = event.key()
if key == Qt.Key_Left:
if self.direction != 2:
if self.direction != 1:
self.direction = 2
# if direction is not up
if self.direction != 4:
self.direction = 3
# if up key is pressed
if self.direction != 3:
# set direction to up
self.direction = 4
if self.direction == 1:
if self.current_x_head & lt
0:
self.current_x_head = Board.WIDTHINBLOCKS - 1
if self.direction == 2:
if self.current_x_head == Board.WIDTHINBLOCKS:
self.current_x_head = 0
if self.direction == 3:
if self.current_y_head == Board.HEIGHTINBLOCKS:
self.current_y_head = 0
if self.direction == 4:
if self.current_y_head & lt
0:
self.current_y_head = Board.HEIGHTINBLOCKS
self.snake.insert(0, head)
if not self.grow_snake:
self.snake.pop()
else:
# show msg in status bar
self.msg2statusbar.emit(str(len(self.snake)-2))
self.grow_snake = False
# checking timer id
if event.timerId() == self.timer.timerId():
self.move_snake()
self.is_food_collision()
self.is_suicide()
self.update()
def is_suicide(self):
# if collision found
if self.snake[i] == self.snake[0]:
self.msg2statusbar.emit(str(& quot
))
self.setStyleSheet(& quot
background-color: black
& quot
self.timer.stop()
self.update()
def is_food_collision(self):
if pos == self.snake[0]:
self.food.remove(pos)
self.drop_food()
# grow the snake
self.grow_snake = True
def drop_food(self):
x = random.randint(3, 58)
y = random.randint(3, 38)
# if position matches
self.drop_food()
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.
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
# importing libraries
import sys
class Window(QMainWindow):
def __init__(self):
super().__init__()
# setting title
self.setWindowTitle("Age calculator")
# setting geometry
# calling method
self.UiComponents()
self.show()
def UiComponents(self):
# font
font.setBold(True)
font.setItalic(True)
font.setUnderline(True)
head.setFont(font)
# setting alignment of the head
head.setAlignment(Qt.AlignCenter)
head.setStyleSheet("color : green;")
# D.O.B label
# setting geometry
dob.setAlignment(Qt.AlignCenter)
dob.setFont(QFont('Times', 10))
# setting geometry
given.setAlignment(Qt.AlignCenter)
given.setFont(QFont('Times', 10))
self.first = QDateEdit(self)
# setting geometry
self.first.setAlignment(Qt.AlignCenter)
self.first.setFont(QFont('Arial', 9))
self.first.dateChanged.connect(self.first_action)
self.second = QDateEdit(self)
# setting geometry
self.second.setAlignment(Qt.AlignCenter)
self.second.setFont(QFont('Arial', 9))
self.second.dateChanged.connect(self.second_action)
color = QGraphicsColorizeEffect()
color.setColor(Qt.darkGreen)
calculate.setGraphicsEffect(color)
calculate.clicked.connect(self.find_age)
self.result = QLabel(self)
# setting geometry
self.result.setAlignment(Qt.AlignCenter)
self.result.setFont(QFont('Times', 12))
# setting stylesheet
self.result.setStyleSheet("QLabel"
"{"
"background : lightgrey;"
"}")
# making label multi line
self.result.setWordWrap(True)
self.first.setDate(QDate(2000, 1, 1))
self.second.setDate(QDate(2020, 1, 1))
def first_action(self):
date = self.second.date()
self.first.setMaximumDate(date)
def second_action(self):
date = self.first.date()
self.second.setMinimumDate(date)
# method called by the push button
def find_age(self):
get_Qdate1 = self.first.date()
birth_year = get_Qdate1.year()
birth_month = get_Qdate1.month()
birth_day = get_Qdate1.day()
get_Qdate2 = self.second.date()
given_year = get_Qdate2.year()
given_month = get_Qdate2.month()
given_day = get_Qdate2.day()
month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
given_month = given_month - 1
given_day = given_day + month[birth_month - 1]
# the difference
given_year = given_year - 1
given_month = given_month + 12
App = QApplication(sys.argv)
# create the instance of our Window
window = Window()
sys.exit(App.exec())
Python3
# importing libraries
import random
import sys
class Window(QMainWindow):
def __init__(self):
super().__init__()
# setting title
self.setWindowTitle("Python ")
# setting geometry
self.UiComponents()
self.show()
# number
self.number = 0
def UiComponents(self):
# font
font.setBold(True)
font.setItalic(True)
font.setUnderline(True)
head.setFont(font)
# setting alignment of the head
head.setAlignment(Qt.AlignCenter)
color = QGraphicsColorizeEffect(self)
color.setColor(Qt.darkCyan)
head.setGraphicsEffect(color)
self.info.setWordWrap(True)
self.info.setFont(QFont('Times', 13))
self.info.setAlignment(Qt.AlignCenter)
self.info.setStyleSheet("QLabel"
"{"
"background : lightgrey;"
"}")
# creating a spin box to set the number
self.spin = QSpinBox(self)
self.spin.setRange(1, 20)
self.spin.setAlignment(Qt.AlignCenter)
self.spin.setFont(QFont('Times', 15))
check.clicked.connect(self.check_action)
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)
start.clicked.connect(self.start_action)
reset_game.clicked.connect(self.reset_action)
def start_action(self):
self.info.setStyleSheet("QLabel"
"{"
"background : lightgrey;"
"}")
def check_action(self):
user_number = self.spin.value()
if user_number == self.number:
self.info.setText("Correct Guess")
self.info.setStyleSheet("QLabel"
"{"
"background : lightgreen;"
"}")
elif user_number < self.number:
# giving hint
else:
# giving hint
def reset_action(self):
self.info.setStyleSheet("QLabel"
"{"
"background : lightgrey;"
"}")
self.info.setText("Welcome")
window = Window()
sys.exit(App.exec())
import random
import sys
class Window(QMainWindow):
def __init__(self):
super().__init__()
# setting title
self.setWindowTitle("Python ")
# setting geometry
# calling method
self.UiComponents()
self.show()
# words
# current word
self.current_text = ""
def UiComponents(self):
# font
font.setBold(True)
font.setItalic(True)
font.setUnderline(True)
head.setFont(font)
head.setAlignment(Qt.AlignCenter)
color = QGraphicsColorizeEffect(self)
color.setColor(Qt.darkCyan)
head.setGraphicsEffect(color)
self.j_word = QLabel(self)
# setting geometry
self.j_word.setGeometry(30, 80, 260, 50)
# setting font
self.j_word.setFont(QFont('Times', 12))
# setting alignment
self.j_word.setAlignment(Qt.AlignCenter)
self.input = QLineEdit(self)
# setting geometry
# setting alignment
self.input.setAlignment(Qt.AlignCenter)
# setting geometry
self.check.clicked.connect(self.check_action)
# result label
self.result = QLabel(self)
# setting geometry
# setting font
self.result.setFont(QFont('Times', 13))
# setting alignment
self.result.setAlignment(Qt.AlignCenter)
start.clicked.connect(self.start_action)
reset.clicked.connect(self.reset_action)
def check_action(self):
text = self.input.text()
if text == self.current_text:
self.result.setText("Correct Answer")
self.result.setStyleSheet("background : lightgreen;")
else:
self.result.setText("Wrong Answer")
self.result.setStyleSheet("background : red;")
def start_action(self):
# selecting one word
self.current_text = random.choice(self.words)
jumbled = ''.join(random_word)
self.j_word.setText(jumbled)
self.result.setText("")
self.input.setText("")
def reset_action(self):
self.input.setText("")
self.j_word.setText("")
self.result.setText("")
App = QApplication(sys.argv)
window = Window()
sys.exit(App.exec())
Conclusion