[go: up one dir, main page]

0% found this document useful (0 votes)
62 views62 pages

PyQt5 Programming Tutorial For Beginners

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
62 views62 pages

PyQt5 Programming Tutorial For Beginners

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 62

PYQT5

PROGRAMMING
TUTORIAL FOR
BEGINNERS

A BEGINNER’S INTRODUCTION TO
DESKTOP APPLICATION DEVELOPMENT
RAVI PRASAD
1
PYQT5
PROGRAMMING
TUTORIAL FOR
BEGINNERS
dfclE
c*
A BEGINNER’S INTRODUCTION TO
DESKTOP APPLICATION DEVELOPMENT
RAVI PRASAD

2
PyQt5 Programming Tutorial for
Beginners : A Beginner’s
Introduction to Desktop Application
Development
Author
Ravi Prasad
Copyright © 2024 kdp copyright All rights reserved.
No part of this publication may be reproduced, distributed, or transmitted in any
form or by any means, including photocopying, recording, or other electronic
or mechanical methods, without the prior written permission of the publisher,
except in the case of brief quotations embodied in reviews and certain other
non-commercial uses permitted by copyright law.

Table Of Contents

Chapter - 1 : Introduction
Supporting Environments
Windows
Chapter - 2 : What’s New
Chapter - 3 : Hello World
Chapter - 4 : Major Classes
Chapter - 5 : Using Qt Designer
Chapter - 6 : Signals & Slots
Using Qt Designer's Signal/Slot Editor
Building Signal-slot Connection

3
Example
Output
Chapter - 7 : Layout Management
setGeometry() syntax
Chapter - 8 : Basic Widgets
Chapter - 9 : QDialog Class
Example
Chapter - 10 : QMessageBox
Example
Chapter - 11 : Multiple Document Interface
Example
Chapter - 12 : Drag and Drop
Example
Chapter - 13 : Database Handling
Example
Example
Chapter - 14 : Drawing API
Example
Chapter - 15 : BrushStyle Constants
Brush Style Constants
Predefined QColor Styles
Predefined QColor Objects
Chapter - 16 : QClipboard
Example
Chapter - 17 : QPixmap Class
Example

4
Chapter - 1 : Introduction
PyQt is a GUI widgets toolkit. It is a Python interface for Qt, one of the
most powerful, and popular cross-platform GUI libraries. PyQt was developed
by RiverBank Computing Ltd. The latest version of PyQt can be downloaded
from its official website − riverbankcomputing.com
PyQt API is a set of modules containing a large number of classes and functions.
While the QtCore module contains non-GUI functionality for working with file
and directory etc., the QtGui module contains all the graphical controls. In
addition, there are modules for working with XML (QtXml), SVG (QtSvg), and
SQL (QtSql), etc.
A list of frequently used modules is given below −
1. QtCore − Core non-GUI classes used by other modules
2. QtGui − Graphical user interface components
3. QtMultimedia − Classes for low-level multimedia programming 4.
QtNetwork − Classes for network programming
5. QtOpenGL − OpenGL support classes
6. QtScript − Classes for evaluating Qt Scripts
7. QtSql − Classes for database integration using SQL
8. QtSvg − Classes for displaying the contents of SVG files
9. QtWebKit − Classes for rendering and editing HTML
10.
QtXml − Classes for handling XML
11.
QtWidgets − Classes for creating classic desktop-
style UIs
12.
QtDesigner − Classes for extending Qt Designer

Supporting Environments
PyQt is compatible with all the popular operating systems including Windows,
Linux, and Mac OS. It is dual licensed, available under GPL as well as
commercial licence. The latest stable version is PyQt5-5.13.2.

5
Windows
Wheels for 32-bit or 64-bit architecture are provided that are compatible with
Python version 3.5 or later. The recommended way to install is using PIP
utility −
pip3 install PyQt5

To install development tools such as Qt Designer to support PyQt5 wheels,


following is the command −
pip3 install pyqt5-tools

You can also build PyQt5 on Linux/macOS from the source code
www.riverbankcomputing.com/static/Downloads/PyQt5

Chapter - 2 : What’s New


PyQt5 API is not automatically compatible with earlier versions. Hence,
Python code involving PyQt4 modules should be upgraded manually by
making relevant changes. In this chapter, main differences between PyQt4
and PyQt5 have been listed.
PyQt5 is not supported on versions of Python earlier than v2.6.
PyQt5 doesn't support connect() method of QObject class for connection
between signal and slot. Hence the usage can no more be implemented −
QObject.connect(widget, QtCore.SIGNAL(‘signal name’), slot_function)

Only the following syntax is defined − widget.signal.connect(slot_function)

Classes defined in earlier QtGui modules have been distributed in QtGui,


QtPrintSupport and QtWidgets modules.

6
In the new QFileDialog class, The getOpenFileNameAndFilter() method
is replaced by getOpenFileName(), getOpenFileNamesAndFilter() by
getOpenFileNames() and getSaveFileNameAndFilter() by
getSaveFileName(). Older signatures of these methods also have changed.
PyQt5 doesn’t have a provision to define a class that is subclassed from
more than one Qt class.
pyuic5 utility (to generate Python code from Designer's XML file) does not
support the --pyqt3-wrapper flag.
pyrcc5 does not support the -py2 and -py3 flags. The output of pyrcc5 is
compatible with all versions of Python v2.6 onwards.
PyQt5 always invokes sip.setdestroyonexit() automatically and calls the C++
destructor of all wrapped instances that it owns.

Chapter - 3 : Hello World


Creating a simple GUI application using PyQt involves the following steps

1. Import QtCore, QtGui and QtWidgets modules from PyQt5
package.
2. Create an application object of QApplication class.
3. A QWidget object creates a top level window. Add a QLabel
object in it.
4. Set the caption of the label as "hello world".
5. Define the size and position of the window by the setGeometry()
method.
6. Enter the mainloop of the application by app.exec_() method.

Following is the code to execute Hello World program in PyQt −


sys import
from PyQt5. t* impor
from PyQt5. imp QtGui
* ort
from PyQt5 QtWidgets import *

7
def
wndow ():
app QApplication = (sys.arg )
w QWidget( ) =
b QLab el w)=
b setText o World!")
("Hell
w. (setGe
0 ,100,200,50)
ometry
b. (50,2 ) move
w setWindowTitle("PyQt5")
.show() w
sys p exec_.exit(ap
())
if __name == '__main__' __ :
window ( )
The above code produces the following output −
■ PyQt5 - □ X

Hello World!

It is also possible to develop an object oriented solution of the above code.


1. Import QtCore, QtGui and QtWidgets modules from PyQt5
package.
2. Create an application object of QApplication class.
3. Declare window class based on QWidget class
4. Add a QLabel object and set the caption of the label as "hello
world".
5. Define the size and position of the window by the setGeometry()
method.
6. Enter the mainloop of the application by app.exec_() method.

Following is the complete code of the object oriented solution −


sys import
from PyQt5. t* impor
from PyQt5. imp QtGui
* ort
from Q tWidgets
PyQt5.import *
class window ): (QWidget
def __init__( parent =

8
super
dow, (win
self).__init__ parent)
sel f (20 ,50) resize
sel f setWindowTitle ("PyQt5")
sel f label = e( self) QLab
sel f label ( "Hello.setWorld")
Text
font QFont() =
font setFamily Arial" ("
font setP .( ) ointSize 16
sel f label.setFont f ont)
s elf.l .move( 5020 )
def ain m
app sys.argv)
= QApplication(
ex = dow( ) win
ex. how()
sys it(app.exec_())
if me__ = __na '__main__':
() main
■ ' PyQt5 - X

Hello World

Chapter - 4 : Major Classes


PyQt API is a large collection of classes and methods. These classes are
defined in more than 20 modules.
Following are some of the frequently used modules −

Sr.N Modules & Description


o.

1 QtCore

9
Core non-GUI classes used by other modules

2 QtGui
Graphical user interface components

3 QtMultimedia
Classes for low-level multimedia programming

QtNetwork
4 Classes for network programming

QtOpenGL
5 OpenGL support classes

QtScript
6 Classes for evaluating Qt Scripts

QtSql
7 Classes for database integration using SQL

QtSvg
8 Classes for displaying the contents of SVG files

QtWebKit
Classes for rendering and editing HTML
9
QtXml
Classes for handling XML
10
QtWidgets
Classes for creating classic desktop-style UIs.
11
QtDesigner
Classes for extending Qt Designer
12
QtAssistant

13

10
Support for online help

PyQt5 development tools is a collection of useful utilities for Qt


development. Following is a select list of such utilities −

Sr. No. Tool Name & Description

1
assistant
Qt Assistant documentation tool
2
pyqt5designer
Qt Designer GUI layout tool
3
linguist
Qt Linguist translation tool
4
lrelease
compile ts files to qm files
5
pylupdate5
extract translation strings and generate or update ts files
6
qmake
Qt software build tool
7
pyqt5 qml scene QML file viewer

8 pyqmlviewer QML file viewer

pyrcc5
9 Qt resource file compiler

pyuic5
10 Qt User Interface Compiler for generating code from ui files

11
11 pyqmltestrunner
running unit tests on QML code

12 qdbus
command-line tool to list D-Bus services

13 QDoc
documentation generator for software projects.

14 Qhelpgenerator
generating and viewing Qt help files.

15 qmlimportscanner
parses and reports on QML imports

PyQt API contains more than 400 classes. The QObject class is at the top of
class hierarchy. It is the base class of all Qt objects. Additionally,
QPaintDevice class is the base class for all objects that can be painted.
QApplication class manages the main settings and control flow of a GUI
application. It contains a main event loop inside which events generated by
window elements and other sources are processed and dispatched. It also
handles system-wide and application-wide settings.
QWidget class, derived from QObject and QPaintDevice classes, is the base
class for all user interface objects. QDialog and QFrame classes are also
derived from QWidget class. They have their own sub-class system.
Here is a select list of frequently used widgets

Sr. No. Widgets & Description

1
QLabel
Used to display text or image
2
QLineEdit
Allows the user to enter one line of text

12
3 QTextEdit
Allows the user to enter multi-line text

4 QPushButton
A command button to invoke action

5 QRadioButton
Enables to choose one from multiple options

6 QCheckBox
Enables choice of more than one options

7 QSpinBox
Enables to increase/decrease an integer value

8 QScrollBar
Enables to access contents of a widget beyond display aperture

9 QSlider
Enables to change the bound value linearly.

10 QComboBox
Provides a dropdown list of items to select from

11 QMenuBar
Horizontal bar holding QMenu objects

12 QStatusBar
Usually at the bottom of QMainWindow, it provides status information.

QToolBar
13 Usually at the top of QMainWindow or floating. Contains action buttons

QListView
Provides a selectable list of items in ListMode or IconMode
14

13
15 QPixmap
Off-screen image representation for display on QLabel or
QPushButton object

16 QDialog
Modal or modeless window which can return information to parent window

A typical GUI based application’s top level window is created by


QMainWindow widget object. Some widgets as listed above take their
appointed place in this main window, while others are placed in the central
widget area using various layout managers.
The following diagram shows the QMainWindow framework −

Menu Bar Toolbar


Areas

Dock Window Areas

Central Widget

Status Bar

Chapter - 5 : Using Qt Designer


The PyQt installer comes with a GUI builder tool called Qt Designer. Using
its simple drag and drop interface, a GUI interface can be quickly

14
built without having to write the code. It is, however, not an IDE such as
Visual Studio. Hence, Qt Designer does not have the facility to debug and
build the application.
Start Qt Designer application which is a part of development tools and
installed in the scripts folder of the virtual environment.
Q Qt Designer O X

Ale
Edit Fgrm View Settings Window Help

!M r 9 B9 9
Widget Box
Object Inspector ft X
Inter

3 Vertical Layout JU HcrtZOlMal Layout


$
Grid Layout
Property Editor
Form Layout

XmHorizontal Space
J Vertical Space Property Value
Buttons

Push Button

Tool Button
Action Editor
Radio Button

Check 8o«

Command Link Button Name Used

Dialog Button Box

v Item Views (Model-Baserf)


List View

*L.Q Tree View


Sflnal/SW Ed Action Ed Re*oj’ce&o«v

Start designing GUI interface by choosing File → New menu.

15
L*. New Form - Qt Designer

templatesXforms Dialog with Buttons Bottom


Dialog with Buttons Right Dialog without Buttons
Main Window
Widget
Widgets
QDockWidget
QFrame QGroupBox
QScrollArea
QMdiArea QTabWidget QToolBox
QStackedWidget QWizard
QWizardPage

Embedded Design

Device:

Screen Size: Default size

0 Show this Dialog on Startup

Create Open... Recent ▼ Close

You can then drag and drop required widgets from the widget box on the left
pane. You can also assign value to properties of the widget laid on the form.

16
O Qt Designer

File
Edit Form Vie* Jettings Window Help

W.dgetBox Object Inspector

loiter

*'xl Oia,<>9 Button Box


| Object Class
Item Views (Model • Based)
Item Widgets (Item-Based) 4> Form QWidget
v
Containers label QLabel
Input Widgets
Combo Box
QLineEd'it
Font Combo Box

line Edit
Maths
Text Edit

Plain Text Edit


Add
Property Value

> text PhySrCS


textFormat AutoText

Signal Re<
ami r Horizontal Scroll Bar

Q| Vertical Scroll Bar

Horizontal Slider

The designed form is saved as demo.ui. This ui file contains XML


representation of widgets and their properties in the design. This design is
translated into Python equivalent by using pyuic5 command line utility.
This utility is a wrapper for the uic module of Qt toolkit. The usage of pyuic5 is
as follows −
pyuic5 -x demo.ui -o demo.py

In the above command, -x switch adds a small amount of additional code to the
generated Python script (from XML) so that it becomes a self- executable
standalone application.
if __name__ == "__main__":
ort sys imp
= QtGui app QA pplication(sys.argv)
D alog = QtGu . ()
ui = ialog Ui_D ()
ui ) pUi(D
.setu ialog
. Dia logshow
()
( app. sys.exit
())

17
The resultant python script is executed to show the following dialog box −
python demo.py

■J Form — X

Physics

Maths

Add

Total

The user can input data in input fields but clicking on the Add button will not
generate any action as it is not associated with any function. Reacting to user-
generated responses is called event handling.

Chapter - 6 : Signals & Slots


Unlike a console mode application, which is executed in a sequential manner, a
GUI based application is event driven. Functions or methods are executed in
response to user’s actions like clicking on a button, selecting an item from a
collection or a mouse click etc., called events.
Widgets used to build the GUI interface act as the source of such events. Each
PyQt widget, which is derived from the QObject class, is designed to emit a
‘signal’ in response to one or more events. The signal on its own
does not perform any action. Instead, it is ‘connected’ to a ‘slot’. The slot can
be any callable Python function.

Using Qt Designer's Signal/Slot Editor

18
First design a simple form with a LineEdit control and a PushButton.
- untitled*

PushButton

It is desired that if a button is pressed, the contents of the text box should be
erased. The QLineEdit widget has a clear() method for this purpose. Hence, the
button’s clicked signal is to be connected to the clear() method of the text box.
To start with, choose Edit signals/slots from the Edit menu (or press F4). Then
highlight the button with mouse and drag the cursor towards the textbox

19
- untitled’

As the mouse is released, a dialog showing signals of button and methods of


slot will be displayed. Select clicked signal and clear() method
O Configure Connection - Qt Designer X

pushButton (QPushButton) meEdit (QLineEdit)

Edit...
clickedO clearQ
clicked(bool) copyO
pressedQ cutO
releasedQ pasteO OK Cancel
| |
toggled(bool) redoQ
selectAIIO
undoQ

Edit...

E Show signals and slots inherited from QWidget

The Signal/Slot Editor window at bottom right will show the result −

20
Signal/Slot Editor fi1 X

l » l~

Sender Signal Receiver Slot


pushButton clicked() lineEdit clear()

Signal/Slot Editor Action Editor Resource Browser

Save ui and Build and Python code from ui file as shown in the below code

pyuic5 -x signalslot.ui -o signalslot.py

Generated Python code will have the connection between signal and slot by the
following statement −
self.pushButton.clicked.connect(self.lineEdit.clear)

Run signalslot.py and enter some text in the LineEdit. The text will be cleared if
the button is pressed.

Building Signal-slot Connection


Instead of using Designer, you can directly establish signal-slot connection by
following syntax −
widget.signal.connect(slot_function)

Suppose if a function is to be called when a button is clicked. Here, the clicked


signal is to be connected to a callable function. It can be achieved in any of the
following technique −
button.clicked.connect(slot_function)

Example
In the following example, two QPushButton objects (b1 and b2) are added
in the QDialog window. We want to call functions b1_clicked() and

21
b2_clicked() on clicking b1 and b2 respectively.
When b1 is clicked, the clicked() signal is connected to b1_clicked()
function −
b1.clicked.connect(b1_clicked())

When b2 is clicked, the clicked() signal is connected to b2_clicked()


function.
sys import
from PyQt5. t* impor
from PyQt5. imp QtGui
* ort
from PyQt5 QtWidgets import *
def window():
app = QApplication (sys. gv)
win = QDialog ()
b1 = (win)
b1. "Button1 "
b1. (50 20)
b1. (b1_clicked )

b2 QPu shButton
= (w in)
b2 setText Button2" ("
b2. ( 50 ) 50,
b2. (b2_clicked)

win. ( 100, , , )
win .setWindowTitle("PyQt5")
win . () show
sys. (app. )
def
b1 (): _clicked
print "Button 1 clicked")
def
b2 (): _clicked
print "Button 2 clicked")

22
if __name__ == '__main__':
window()
The above code produces the following output −
■ PyQt5 X

Button1

Button2

Output
Button 1 clicked Button 2 clicked

Chapter - 7 : Layout Management


A GUI widget can be placed inside the container window by specifying its
absolute coordinates measured in pixels. The coordinates are relative to the
dimensions of the window defined by the setGeometry() method.

setGeometry() syntax
QWidget.setGeometry(xpos, ypos, width, height)

In the following code snippet, the top level window of 300 by 200 pixels
dimensions is displayed at position (10, 10) on the monitor.
sys import
from PyQt4 import QtGui
wi def ndow
():
app = QtGui.QApplication(sys.

23
w QtGui QWidget( = )
b QtGui. = on( w)
b setText( "Hello World!")
b. move (50,20)
w. setGeometry
(10, 0, 0, )
w setWindowTitle(“ PyQt”)
.show() w
sys .exit(ap
p. xec_() )
if __name == '__main__': __
window ( )
A PushButton widget is added in the window and placed at a position 50 pixels
towards right and 20 pixels below the top left position of the window.
This Absolute Positioning, however, is not suitable because of following reasons

1. The position of the widget does not change even if the window is
resized.
2. The appearance may not be uniform on different display devices
with different resolutions.
3. Modification in the layout is difficult as it may need redesigning
the entire form.
• PyQtS Window X
• PyQt5 Window — □ X
Hello World'

Hello World!

PyQt API provides layout classes for more elegant management of


positioning of widgets inside the container. The advantages of Layout
managers over absolute positioning are −
1. Widgets inside the window are automatically resized.

24
2. Ensures uniform appearance on display devices with different
resolutions.
3. Adding or removing a widget dynamically is possible without
having to redesign.

Qt toolkit defines various layouts that can be used with Qt Designer utility.
O Ct Designer

Ale
£dt F&rm View Settings Window Help

igfB S W S H X S » S» H
Widget Bo.
Object Inspector
iter
Piter
j
layouts
Object CUM
3
Verticil layout
J]
Horizontal layout
Layout Managers
'ii Grid layout
Property Editor X
rr Form Layout
Petr _ |oj

S'Jtton-5
Property Value
ItemDnpUyWdgets
Views (Model Based)
item Widgets (Mem- Based)
> Containers
Input
Widgets Action Editor

5 x

z ■
Name
Used

S*yMi5
Art Rescue

Here is the list of Classes which we will discuss one by one in this chapter.

Sr. Classes & Description


No.

1 QBoxLayout
QBoxLayout class lines up the widgets vertically or horizontally.
Its derived classes are QVBoxLayout (for arranging widgets vertically) and
QHBoxLayout (for arranging widgets horizontally).

2 QGridLayout
A GridLayout class object presents a grid of cells arranged in rows and
columns. The class contains the addWidget() method. Any widget can be
added by specifying the number of rows and columns of the cell.

25
3 QFormLayout
QFormLayout is a convenient way to create two column forms, where each
row consists of an input field associated with a label. As a convention, the left
column contains the label and the right column contains an input field.

Chapter - 8 : Basic Widgets


Here is the list of Widgets which we will discuss one by one in this chapter.

Sr. Widgets & Description


No

1 QLabel
A QLabel object acts as a placeholder to display non-editable text or image,
or a movie of animated GIF. It can also be used as a mnemonic key for other
widgets.

2 QLineEdit
QLineEdit object is the most commonly used input field. It provides a box in
which one line of text can be entered. In order to enter multi-line text, a
QTextEdit object is required.

3 QPushButton
In PyQt API, the QPushButton class object presents a button which when
clicked can be programmed to invoke a certain function.

4 QRadioButton
A QRadioButton class object presents a selectable button with a
text label. The user can select one of many options presented on the form. This
class is derived from the QAbstractButton class.

5 QCheckBox

26
A rectangular box before the text label appears when a QCheckBox object is
added to the parent window. Just like the QRadioButton, it is also a selectable
button.

6 QComboBox
A QComboBox object presents a dropdown list of items to select from. It
takes minimum screen space on the form required to display only the
currently selected item.

7 QSpinBox
A QSpinBox object presents the user with a textbox which displays an integer
with an up/down button on its right.

8 QSlider Widget & Signal


The QSlider class object presents the user with a groove over which a handle
can be moved. It is a classic widget to control a bounded value.

QMenuBar, QMenu & QAction


9 A horizontal QMenuBar just below the title bar of a QMainWindow object is
reserved for displaying QMenu objects.

QToolBar
10 A QToolBar widget is a movable panel consisting of text buttons, buttons
with icons or other widgets.

QInputDialog
11 This is a preconfigured dialog with a text field and two buttons, OK and Cancel.
The parent window collects the input in the text box after the user clicks on Ok
button or presses Enter.

QFontDialog
12 Another commonly used dialog, a font selector widget is the visual appearance
of QDialog class. Result of this dialog is a Qfont object, which can be
consumed by the parent window.

QFileDialog
13

27
This widget is a file selector dialog. It enables the user to navigate through the
file system and select a file to open or save. The dialog is invoked either
through static functions or by calling exec_() function on the dialog object.

QTab
14 If a form has too many fields to be displayed simultaneously, they can be
arranged in different pages placed under each tab of a Tabbed Widget. The
QTabWidget provides a tab bar and a page area.

QStacked
The Function of QStackedWidget is similar to QTabWidget. It also helps in the
15 efficient use of the window's client area.

QSplitter
This is another advanced layout manager which allows the size of child
16 widgets to be changed dynamically by dragging the boundaries between
them. The Splitter control provides a handle that can be dragged to resize the
controls.

QDock
A dockable window is a sub window that can remain in floating state or can be
17 attached to the main window at a specified position. Main window object of
QMainWindow class has an area reserved for dockable windows.

QStatusBar
The QMainWindow object reserves a horizontal bar at the bottom
as the status bar. It is used to display either permanent or contextual status
18 information.

QList
QListWidget class is an item-based interface to add or remove
items from a list. Each item in the list is a QListWidgetItem object. ListWidget
19 can be set to be multiselectable.

QScrollBar

20

28
A scrollbar control enables the user to access parts of the document that are
outside the viewable area. It provides a visual indicator of the current position.

QCalendar
21 QCalendar widget is a useful date picker control. It provides a month-based
view. The user can select the date by the use of the mouse or the keyboard,
the default being today’s date.

Chapter - 9 : QDialog Class


A QDialog widget presents a top level window mostly used to collect
responses from the user. It can be configured to be Modal (where it blocks its
parent window) or Modeless (the dialog window can be bypassed).
PyQt API has a number of preconfigured Dialog widgets such as InputDialog,
FileDialog, FontDialog, etc.

Example
In the following example, the WindowModality attribute of the Dialog
window decides whether it is modal or modeless. Any one button on the dialog
can be set to be default. The dialog is discarded by the QDialog.reject() method
when the user presses the Escape key.
A PushButton on a top level QWidget window, when clicked, produces a
Dialog window. A Dialog box doesn’t have minimise and maximise controls
on its title bar.
The user cannot relegate this dialog box in the background because its
WindowModality is set to ApplicationModal.
sys import
from PyQt5. QtCore
import *
from PyQt5. import *

29
from PyQt5.QtWidgets import *
wndow def :
app QApplication = (sys.argv)
w = QWidget ()
btn QPus = (w) hButton
btn setText("H ello World!")
btn. (1 0 ,50)
.clicked.conne
btn c ( showdialog
w setWindowTitle( "PyQt Dialog
show() w.
sys. ( pp. ())
def():
showdialog
dlg = QDialog ()
b1 = QP
ushButton("ok",dlg)
b1. move (50,50)
dlg .setWindowTitle
("Dialog" ) 9. PyQt5 — QDialog Class
dl .setWindowModality(Qt .ApplicationModal
dlg exec_()
if __name__ == '__main__':
window()
The above code produces the following output. Click on button in main
window and dialog box pops up −

30
■ PyQt Dialog demo □ X

Hello World!

Chapter - 10 : QMessageBox
QMessageBox is a commonly used modal dialog to display some informational
message and optionally ask the user to respond by clicking any one of the
standard buttons on it. Each standard button has a predefined caption, a role and
returns a predefined hexadecimal number.
Important methods and enumerations associated with QMessageBox class are
given in the following table −

Sr. Methods & Description


No.

1 setIcon()
Displays predefined icon corresponding to severity of the message
1. Question
2. Information

31
3. Warning Critical
4.

2 setText()
Sets the text of the main message to be displayed

3 setInformativeText()
Displays additional information

4 setDetailText()
Dialog shows a Details button. This text appears on clicking it

5 setTitle()
Displays the custom title of dialog

6 setStandardButtons()
List of standard buttons to be displayed. Each button is associated with
QMessageBox.Ok 0x00000400
QMessageBox.Open 0x00002000
QMessageBox.Save 0x00000800
QMessageBox.Cancel 0x00400000
QMessageBox.Close 0x00200000
QMessageBox.Yes 0x00004000
QMessageBox.No 0x00010000
QMessageBox.Abort 0x00040000
QMessageBox.Retry 0x00080000
QMessageBox.Ignore 0x00100000

setDefaultButton()
Set the button as default. It emits the clicked signal if Enter is pressed
7
setEscapeButton()
Sets the button to be treated as clicked if the escape key is pressed
8

32
Example
In the following example, clicking the button on the top level window, the
connected function displays the messagebox dialog.
msg = QMessageBox()
msg.setIcon(QMessageBox.Information)
msg.setText("This is a message box")
msg.setInformativeText("This is additional information")
msg.setWindowTitle("MessageBox demo")
msg.setDetailedText("The details are as follows:")

setStandardButton() function displays desired buttons.


msg.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)

buttonClicked() signal is connected to a slot function, which identifies the


caption of source of the signal.
msg.buttonClicked.connect(sms btn)

The complete code for the example is as follows −


sys import
from PyQt5. t* impor
from PyQt5. imp QtGui
* ort
from PyQt5 QtWidgets import *
def window():
app = QApplication (sys. )
w = QWidget()
b =QPushButton w)
b. ("Show message!")

b. 0050)move (1
b. clicked
.connect(showdialog )
w setWindowTitle("PyQt MessageBox demo")
.show() w
sys. (app exec_ ())

33
def g
msg = QMessageBox()
msg.setIcon(QMessageBox .Information)

msg.setText ("This is
message a
box")
msg .setInformativeText ("This is information")
additional
msg.setWindowTitle( )
"MessageBox demo"
msg (" he details are as follows:")
.setDetailedText
msg.setStandardButtons MessageBo (Q Ok | QMessageBox.Cancel)
msg.buttonClicked ( .connect
retval = msg. ()
def
ms (i): gbtn
print "Button pressed is:", . ())
if __name__ == '__main__':
window()
The above code produces the following output. Message Box pops up when
main windows’ button is clicked −
■ PyQt MessageBox demo □ X
This is a message box

This is additional information

Show message1 OK Hide Details...


Cancel

The details are as follows:

If you click on Ok or Cancel button on MessageBox, the following output is


produced on the console −
Button pressed is: OK
Button pressed is: Cancel

34
Chapter - 11 : Multiple Document
Interface
A typical GUI application may have multiple windows. Tabbed and stacked
widgets allow one such window to be activated at a time. However, many times
this approach may not be useful as the view of other windows is hidden.
One way to display multiple windows simultaneously is to create them as
independent windows. This is called SDI (single Document Interface). This
requires more memory resources as each window may have its own menu
system, toolbar, etc.
MDI (Multiple Document Interface) applications consume lesser memory
resources. The sub windows are laid down inside the main container with
relation to each other. The container widget is called QMdiArea.
The QMdiArea widget generally occupies the central widget of the
MainWindow object. Child windows in this area are instances of
QMdiSubWindow class. It is possible to set any QWidget as the internal
widget of subWindow object. Sub-windows in the MDI area can be
arranged in cascaded or tile fashion.
The following table lists important methods of QMdiArea class and
QMdiSubWindow class −

Sr. No. Methods & Description

1
addSubWindow()
Adds a widget as a new sub window in MDI area
2
removeSubWindow()
Removes a widget that is internal widget of a subwindow
3
setActiveSubWindow()

35
Activates a subwindow

4 cascadeSubWindows()
Arranges subwindows in MDiArea in a cascaded fashion

5 tileSubWindows()
Arranges subwindows in MDiArea in a tiled fashion

6 closeActiveSubWindow() Closes the active


subwindow

7 subWindowList()
Returns the list of subwindows in MDI Area

8 setWidget()
Sets a QWidget as an internal widget of a QMdiSubwindow instance

QMdiArea object emits subWindowActivated() signal whereas


windowStateChanged() signal is emitted by QMdisubWindow object.

Example
In the following example, the top level window consisting of
QMainWindow has a menu and diarrhoea.
self. mdi
= QMdiArea()
self setCentralWidget(self.mdi)
bar = self ()
file = bar. ( )
file.addAction("New"
file.addAction("cascade"
file.addAction("Tiled")
The Trigger() signal of the menu is connected to the window action()
function.
file.triggered[QAction].connect(self.window action)

36
The new action of the menu adds a subwindow in the MDI area with a title
having an incremental number to it.
MainWindow.
count = ainWindow .count+1
sub ubWindow
= QMdiS ) (
sub. (QTex ())
setWidget tEdit
sub setWindowTitle bwindow"+str(MainWindow.count))
("su
self. . (sub)
ddSubWindow
sub. ()
Cascaded and tiled buttons of the menu arrange currently displayed
subwindows in cascaded and tiled fashion respectively.
The complete code is as follows −
sys import
from PyQt5. t* impor
from PyQt5. imp QtGui
* ort
from PyQt5 QtWidgets import *
class
MainWindow(QMainWindow):
count = 0
__i f parent
de
(self, nit__= None ):
super ainWindow(M , el f __init__(parent)
self. mdi )
= QMdiArea(
self setCentralWidget( self.mdi)
bar = self (
file bar.addM = ile") enu ("F
file addAction ) ("New"
file. ("cascade"
file. ) ("Tiled"
file. triggered
[ QActi on
]. onnect(self.window action)
self. setWindowTitle("MDI demo" )
define window action ( f q):
print ("triggered")

if text() == "Nq.ew":
MainWindow. = MainWindow.count+1

37
=
sub QMdiSubWindow()
sub .setWidget(QTextEdit())
sub .setWindowTitle("subwindow"+str(MainWindow.count))
self addSubWindow(s
.mdi. ub)
sub.show()
if te () q. xt ==
"cascade":
self. i cascadeSubWindows()
if te () q. xt ==
"Tiled":
self. i tileSubWindows()
main(): def
app = QApplication sys.
ex = inWindow()
Ma
ex. () how
sys exit app. ()
if __name__ == '__main__':
main()
Run above code and three windows in cascade and tiled formation −
MDI demo □ X
File

New

cascade

Tiled

38
■ MDI demo - X
File
~ subwindowl
=ir aaif
subwindow2
<=>
a
ni l|-£3«
U subwindow3 1 ii ®

File MDI demo

subwindow2

subwindow3

subwindowl

Chapter - 12 : Drag and Drop


The provision of drag and drop is very intuitive for the user. It is found in
many desktop applications where the user can copy or move objects from

39
one window to another.
MIME based drag and drop data transfer is based on QDrag class.
QMimeData objects associate the data with their corresponding MIME type. It
is stored on a clipboard and then used in the drag and drop process.
The following QMimeData class functions allow the MIME type to be detected
and used conveniently.

Tester Getter Setter MIME Types

hasText() text() setText() text/plain

hasHtml( html() setHtml() text/html


)

hasUrls() urls() setUrls() text/uri-list

hasImag e() imageDat a() setImageDat a() image/ *

hasColor colorData setColorData


() () () application/x- color

Many QWidget objects support the drag and drop activity. Those that allow their
data to be dragged have setDragEnabled() which must be set to true.
On the other hand, the widgets should respond to the drag and drop events
in order to store the data dragged into them.
1. DragEnterEvent provides an event which is sent to the target
widget as dragging action enters it.
2. DragMoveEvent is used when the drag and drop action is in
progress.
3. DragLeaveEvent is generated as the drag and drop action leaves
the widget.
4. DropEvent, on the other hand, occurs when the drop is
completed. The event’s proposed action can be accepted or
rejected conditionally.

40
Example
In the following code, the DragEnterEvent verifies whether the MIME data
of the event contains text. If yes, the event’s proposed action is accepted and
the text is added as a new item in the ComboBox.
sys import
from PyQt5. t* impor
from PyQt5. imp QtGui
* ort
from PyQt5 QtWidgets import *
class combo
(QComboBox):
nit__ de
lf, title , (se ):
f __i
(combo,super
self)._ _init__ ( parent)
self setAcceptDrops True)
f (self, e):
de
dra gEnterEvent
print (e)
.
if e mime Data().hasText()
e. () a
else
e. ()
f , e):
dr opEvent(de self
self. (e mimeData().text())

: t:
class Example(QWidge
__i (self)
de
f nit__
super(Example , self).__init__()
self. ()
def initUI( lf
lo = QFormLayout ( )
lo addRow(QLabe l "Type some text in textbox and drag it into combo
box" )

edit QLineEdit()=
edit setDragEnabled(True)

41
com b
Button", ("
= com self)
loc.aom) (ed it,
ddRow
self.
(lo) setLayout
s elf etWindowTitle (Simple drag and drop')
def ain(): m
app
= QApplication(sys.argv)
ex = ample() Ex
s () ex.how
app.
if __name__ == '__main__':
main()
The above code produces the following output −
• Simple drag and drop — X

Type some text in textbox and drag it into combo box

■ Simple drag and drop — X

Type some text in textbox and drag it into combo box


Hello Python Hello Python

Chapter - 13 : Database Handling


PyQt5 library contains QtSql module. It is an elaborate class system to
communicate with many SQL based databases. Its QSqlDatabase provides
access through a Connection object. Following is the list of currently available
SQL drivers −

Sr.N
o. Driver Type & Description

42
1 QDB2 IBM DB2

EQUIBASE
2 Borland InterBase Driver

QMYSQL MySQL Driver


3
QOCI
Oracle Call Interface Driver
4
QODBC
ODBC Driver (includes Microsoft SQL Server)
5
QPSQL PostgreSQL Driver

QSQLITE
6 SQLite version 3 or above

SQLITE2 SQLite version 2


7

Example
For this chapter, a connection with a SQLite database is established using the
static method −
db = QtSql.QSqlDatabase.addDatabase('QSQLITE')
db.setDatabaseName('sports.db')

Other methods of QSqlDatabase class are as follows −

Sr.
No. Methods & Description

43
1 setDatabaseName()
Sets the name of the database with which connection is sought

setHostName()
2 Sets the name of the host on which the database is installed

setUserName()
3 Specifies the user name for connection

setPassword()
4 Sets the connection object’s password if any

commit()
5 Commits the transactions and returns true if successful

rollback()
6 Rolls back the database transaction

close()
7 Closes the connection

QSqlQuery class has the functionality to execute and manipulate SQL


commands. Both DDL and DML type of SQL queries can be executed. First step
is to create SQlite database using the following statements −
db = QSqlDatabase.addDatabase('QSQLITE')
db.setDatabaseName('sportsdatabase.db')

Next, obtain a Query object with the QSqlQuery() method and call its most
important method exec_(), which takes as an argument a string containing SQL
statements to be executed.
query = QtSql.QSqlQuery()
query.exec_("create table sportsmen(id int primary key, " "firstname
varchar(20), lastname varchar(20))")

44
The following script creates a SQLite database sports.db with a table of
sportspeople populated with five records.
sys import
from PyQt5. i mportQtSql *
from PyQt5 QtCore * import
from PyQt5. imp QtGui ort
*
from PyQt5 QtWidgets import *
def
createDB():
db QSqlDatabase.a
= ddDatabase
('QSQLITE')
db setDatabaseName( 'sportsdatabase.db')
if not d bopen ():
msg QMe = ssageBox ()
msg.setIcon( QMessageBox
.Critical)
.setText( "Error
msg in Database Creation")
retval = msg . ()
retu r False
query = QSqlQuery( )
query.table sportsmen(
exec_("create
id int primary key, ""firstname varchar(20), lastname varchar(20))")
query. ( "insert into sportsmen values(101, 'Roger',
) 'Federer')"
query. ("insert into sportsmen values(102, 'Christiano', 'Ronaldo')")
query. ( "insert into sportsmen values(103, 'Usain',
) 'Bolt')"
query. ("insert into sportsmen values(104, 'Sachin', 'Tendulkar')")
query. ("insert into sportsmen values(105, 'Saina', 'Nehwal')")
return True
if ==__n ame__
'__main__':
= pplication(sys.argv)
app
QA
createDB()
To confirm that the SQLite database is created with the above records added in
the sportsmen table in it, use a SQLite Gui utility called SQLiteStudio.

45
> SQLiteStudio (3.1.1) - [sportsmen (sports)] x
r*| Database Structure View Tools
Help
X B ft A ft
. 13
Databases S’ x Structure Data Constraints Indexes Triggers DDL
name
«.| ,.i CSQLite3}
■ > sports G rid view Form view
registrations (SQL college
(SQLite3) |
u
A A
'
E] Q- a a a a i Q «
lastname
»i id firstname
Federer 101 Roger
2 102 Christiano Ronaldo
J £ 3 103 Ussain Bolt
"fsj 8 4 104 Sachin Tendulkar
5 105 Saina Nehwal

sportsmen (sports)

QSqlTableModel class in PyQt is a high-level interface that provides an


editable data model for reading and writing records in a single table. This
model is used to populate a QTableView object. It presents to the user a
scrollable and editable view that can be put on any top level window.
A QSqlTableModel object is declared in the following manner −
model = QtSql.QSqlTableModel()

Its editing strategy can be set to any of the following −

QSqlTableModel.OnFieldChange All changes will be applied


immediately

QSqlTableModel.OnRowChange Changes will be applied when the user


selects a different row

QSqlTableModel.OnManualSub mit All changes will be cached until either


submitAll() or revertAll() is called

Example

46
In the following example, sportsperson table is used as a model and the
strategy is set as −
model. setTable)
('sportsmen'
se tEditStrategy(QtSql.
model. . )
model. ()
The QTableView class is part of the Model/View framework in PyQt. The
QTableView object is created as follows −
view = QtGui.
QTableView()
view. (model)
setModel
.setWindowTitle(title)
view
return view
This QTableView object and two QPushButton widgets are added to the top
level QDialog window. Clicked() signal of the add button is connected to
addRow() which performs insertRow() on the model table.
click button. ed.
connect(addrow)
def drow ():
nt model
.rowCount(
pri )
= model.insertRows(model.rowCount(),
ret 1)
print ret
The Slot associated with the delete button executes a lambda function that
deletes a row, which is selected by the user.
btn1.clicked.connect(lambda:
model.removeRow(view1.currentIndex().row()))

The complete code is as follows −


sys import
from PyQt5. i mportQtSql *
from PyQt5 QtCore * import
from PyQt5. imp QtGui ort
*
from PyQt5 QtWidgets import *
initia def lizeModel
(model):
model. ('sportsmen')

47
model. (QSqlTableModel.OnFieldChange)
model.
model. ( 0 Qt.Horizontal, "ID"
model setHeaderData( Qt.Horizontal, "First
model setHeaderData( 1 Qt.Horizontal, "Last name")
cre teView
def odel (title, m
view = QTable View ()
view. (modesetModel
.setWindowTitle(title)
view
return view
def row
( ():
nt mode l pri
rowCount())
= model .insertRows
ret (model.rowCount(), 1)
print (ret)
def
findrow ): (i
delrow = .row()
if __n ame__ == '__m ain__'
app =QApplication ( sys.argv)
db = ITE') ('QSQL
QSqlDatabase.addDatabase
setD ('spo
db. atabaseName )rtsdatabase.db'
QSqlTableModel
model = ()
=- delrow
initializeModel(model)
view1 = TableView
("create Model (View 1)", model)
view1. .connect(findrow)
clicked
= QDialog()dlg
layout QVBoxL = () ayout
layout.addWidget view1)
button = QPus
hButton ( Add a row")
button. co clicked. nnect
(addrow)
layout addWidget button )
btn1 = QPushButton("del a row")

48
btn1 conn.clicked.
(la ect mbda:
r moveRow
model. view1. ( ().row()))
layout. (btn1
dlg.setLayo ut(layout)
dlg.setWindowTitle("Database
dlg.show()
sys.exit(app.
The above code produces the following output −
IB ' Database Demo ? X

ID First name Last name

1 101 Roger Federer

2 102 Christiano Ronaldo

3 103 Ussain Bolt

4 104 Sachin Tendulkar

5 105 Saina Nehwal

6 106 Virat Kohli

Add a row

del a row

Try adding and deleting a few records and go back to SQLiteStudio to


confirm the transactions.

Chapter - 14 : Drawing API


All the QWidget classes in PyQt are sub-classed from the QPaintDevice class.
A QPaintDevice is an abstraction of two dimensional space that can

49
be drawn upon using a QPainter. Dimensions of the paint device are measured
in pixels starting from the top-left corner.
QPainter class performs low level painting on widgets and other paintable
devices such as printers. Normally, it is used in widget’s paint event. The
QPaintEvent occurs whenever the widget’s appearance is updated.
The painter is activated by calling the begin() method, while the end() method
deactivates it. In between, the desired pattern is painted by suitable methods as
listed in the following table.

Sr. Methods & Description


No.

1 begin()
Starts painting on the target device

2 drawArc()
Draws an arc between the starting and the end angle

3 drawEllipse()
Draws an ellipse inside a rectangle

4 drawLine()
Draws a line with endpoint coordinates specified

5 drawPixmap()
Extracts pixmap from the image file and displays it at the specified position

drawPolygon()
6 Draws a polygon using an array of coordinates

drawRect()
7 Draws a rectangle starting at the top-left coordinate with the given width and
height

drawText()
8 Displays the text at given coordinates

50
9 fillRect()
Fills the rectangle with the QColor parameter

10 setBrush()
Sets a brush style for painting

11 setPen()
Sets the colour, size and style of pen to be used for drawing

Example
In the following code, various methods of PyQt's drawing methods are
used.
sys import
from PyQt5. t* impor
from PyQt5. imp QtGui
* ort
from PyQt5 QtWidgets import *
class Example ( QWidget :
nit__(self)
de
f __i :
(Exa mplsuper
, self).__init__()
self initUI( )
in f itUI
( elf):de
self. textrld"
wo = "hello
self. setGeometry
(100,100, 400,30 )
self setWindowTitle('Draw Demo')
self. ()
def p , event): self
( aintEvent
qp = ainter() QP
qp. (
) begin self
qp. setPen ( ))
QColor( Qt .red
qp. setFont , 2 )) Arial'
(Q Font('
qp drawText 0," hello(10,5
Python")
qp. (Q setPen.blu Color
)) (Qt e
qp drawLine(1 , 100 100)100,

51
qp. drawRect(10,
150, 100) 150,
qp setPen(QColor(Qt ellow ) .y
qp. (100, , 50) 50 100,
qp drawPixmap (22 0,1 0 Pixmap("pythonlogo.png"))
qp. (2 ,175,130,70 QBrush(Qt.SolidPattern))
qp.
m ain(): def
app = Ex
QApplication(sys.argv)
ex = .exit
ample ()
sys (app. ()) exec_

if __name__ == '__main__':
main()
The above code produces the following output −
Draw Demo

Chapter - 15 : BrushStyle
Constants

52
In this chapter, we shall learn Brush Style Constants.

Brush Style Constants


Given below are the Brush Style Constants −

Qt.NoBrush No brush pattern

Qt.SolidPattern Uniform colour

Qt.Dense Pattern Extremely dense brush pattern

Qt.HorPattern Horizontal lines

Qt.VerPattern Vertical lines

Qt.CrossPattern Crossing horizontal and vertical lines

Backward diagonal lines


Qt.BDiagPattern
Forward diagonal lines
Qt.FDiagPattern
Crossing diagonal lines
Qt.DiagCrossPatte
rn

Predefined QColor Styles


Given below are the Predefined QColor Styles −

Qt.NoBrush No brush pattern

Qt.SolidPattern Uniform colour

Qt.Dense Pattern Extremely dense brush pattern

Qt.HorPattern Horizontal lines

53
Qt.VerPattern Vertical lines

Qt.CrossPattern Crossing horizontal and vertical lines

Backward diagonal lines


Qt.BDiagPattern
Forward diagonal lines
Qt.FDiagPattern
Crossing diagonal lines
Qt.DiagCrossPatte
rn

Predefined QColor Objects


Given below are the Predefined QColor Objects −

Qt.white

Qt.black

Qt.red

Qt.darkRed

Qt.green

Qt.darkGreen

Qt.blue

Qt.cyan

Qt.magenta

Qt.yellow

Qt.darkYello
w

54
Qt.gray

Custom colour can be chosen by specifying RGB or CMYK or HSV values.

Chapter - 16 : QClipboard
The QClipboard class provides access to a system-wide clipboard that offers a
simple mechanism to copy and paste data between applications. Its action is
similar to the QDrag class and uses similar data types.
QApplication class has a static method clipboard() which returns reference to
clipboard objects. Any type of MimeData can be copied to or pasted from the
clipboard.
Following are the clipboard class methods that are commonly used −

Sr.N Methods & Description


o.

1 clear()
Clears clipboard contents

2 setImage()
Copies QImage into clipboard

3 setMimeData()
Sets MIME data into clipboard

4 setPixmap()
Copies Pixmap object in clipboard

setText()
5 Copies QString in clipboard

55
6 text()
Retrieves text from clipboard

Signal associated with clipboard object is −

Sr.N Method & Description


o.

1 dataChanged() Whenever clipboard data changes

Example
In the following example, two TextEdit objects and two Pushbuttons are
added to a top level window.
To begin with the clipboard object is instantiated. Copy() method of the
textedit object copies the data onto the system clipboard. When the Paste
button is clicked, it fetches the clipboard data and pastes it in another textedit
object.
sys import
from PyQt5. t* impor
from PyQt5. imp QtGui
* ort
from PyQt5 QtWidgets import *

: t:
class Example(QWidge
__i (self)
de
f nit__
super(Example , self).__init__()
self. ()
def initUI(self):
hbox VBoxLayout
= Q()
self.e =QText Edit()
dit1
hbox. (self.ed
add ) it1
self.b =QPush Button
tn1 Copy") ("
hbox. (self ) .btn1

56
self . = QTextEdit()
self. = ( "Paste")
hbox. (self. )
hbox. (self . )
self. . . ( self. )
self. . . ( self pastetext )
self. (hbox)

self. setGeometry
(300, 30 , 300, 200)
self setWindowTitle('Clipboard' )
self.show()

d ef self):
#clipboard.setText(self.edit1.copy())
self. copy() dit1.
print clipboard. ())
=
msg QMes sageBox()
msg.setText(clipboard .text()+" copied on clipboard")
msg.exec_()
pa f stetext
de
(self):
self. setText(clipboard.text())
= QA app (syspplication
. )
clipboard=app clipboard ()
ex = Example()
("
ex. etWindowTitle clipboard Example")
sys exit(app. ())
The above code produces the following output −

57
■ clipboard Example □ X

Tutorialspoint.com PyQt5 Tutorial)

Copy

Paste

* python X

PyQt5 Tutorial copied on clipboard

OK

■ clipboard Example □ X

Tutorialspoint.com PyQt5
Tutorial

Copy

PyQt5 Tutorial

Paste

Chapter - 17 : QPixmap Class

58
QPixmap class provides an off-screen representation of an image. It can be used
as a QPaintDevice object or can be loaded into another widget, typically a label
or button.
Qt API has another similar class QImage, which is optimised for I/O and other
pixel manipulations. Pixmap, on the other hand, is optimised for showing it on
screen. Both formats are interconvertible.
The types of image files that can be read into a QPixmap object are as follows −

BM Windows Bitmap
P

GIF Graphic Interchange Format (optional)

Joint Photographic Experts Group


JPG
Joint Photographic Experts Group
JPE
G
Portable Network Graphics
PN
G
Portable Bitmap
PB
M
Portable Graymap
PG
M
Portable Pixmap
PP
M
X11 Bitmap
XB
M
X11 Pixmap
XP
M

59
Following methods are useful in handling QPixmap object −

Sr.N Methods & Description


o.

1 copy()
Copies pixmap data from a QRect object

fromImage()
2 Converts QImage object into QPixmap

grabWidget()
3 Creates a pixmap from the given widget

grabWindow()
Create pixmap of data in a window
4
Load()
Loads an image file as pixmap
5
save()
Saves the QPixmap object as a file
6
toImage
Converts a QPixmap to QImage
7

The most common use of QPixmap is to display images on a label/button.

Example
The following example shows an image displayed on a QLabel by using the
setPixmap() method.
The complete code is as follows −
sys import
from PyQt5. import *

60
from PyQt5. imp QtGui
* ort
from PyQt5. import *
wi ():def ndow
app = QApplication(sy s argv)
win = QWidget()
l1 QLabel( =
l .setPixmap(QPixmap( "python.png"))
vbox = QVBoxL
ayout()
addWidg et
(l1)
vbox.
win . (vbox)
setLayout
win .setWindowTitle("QPixmap Demo")
win . () show
sys. t app.
if __name__ == '__main__':
window()
The above code produces the following output −
■ QPixmap Demo □

61
Thank You

62

You might also like