python logo


Category: PyQt5

PyQt5 window

If you do not have PyQT5 installed, you should install it first.
In a terminal you can type:


sudo apt-get install python3-pyqt5

If you are on a Windows or Mac computer, you can download PyQT5 from: https://www.riverbankcomputing.com/software/pyqt/download5

Related courses:

PyQt5 window

You can create a PyQT5 window using the code below:


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

class App(QWidget):

def __init__(self):
super().__init__()
self.title = 'PyQt5 simple window - pythonspot.com'
self.left = 10
self.top = 10
self.width = 640
self.height = 480
self.initUI()

def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
self.show()

if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())

We set the window size using the setGeometry(left,top,width,height) method. The window title is set using setWindowTitle(title). Finally show() is called to display the window.

Run with:


python3 window.py

pyqt5-window

If you are new to programming Python PyQt, I highly recommend this book.

Download PyQT5 Code

The output should look similar to the screenshot above (depending on your operating system).

PyQt5 statusbar

PyQt5 supports a window status bar. This is a small bar at the bottom of a window that sometimes appears, it can contain text messages. To add a status bar add the line:


self.statusBar().showMessage('Message in statusbar.')

A statusbar can be added to the main window (QMainWindow). It is one of the methods the class itself contains;

Related course:
Create GUI Apps with PyQt5

PyQt5 statusbar example:
The program below adds a statusbar to a PyQt5 window:


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

class App(QMainWindow):

def __init__(self):
super().__init__()
self.title = 'PyQt5 status bar example - pythonspot.com'
self.left = 10
self.top = 10
self.width = 640
self.height = 480
self.initUI()

def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
self.statusBar().showMessage('Message in statusbar.')
self.show()

if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())

The example creates a window (QMainWindow). We set the screen parameters using:


self.left = 10
self.top = 10
self.width = 640
self.height = 480

Window properties are set in the initUI() method which is called in the constructor. The method:


statusBar().showMessage()

sets the text on the statusbar.

If you are new to programming Python PyQt, I highly recommend this book.

Download PyQT5 Examples

PyQt5 buttons

PyQt5 supports buttons using the QPushButton class. This class is inside the PyQt5.QtWidgets group. The button can be created by calling the constructor QPushButton with the text to display as parameter.

Related course:

Introduction
To use buttons with a PyQt5 application, we need to update our import line:


from PyQt5.QtWidgets import QApplication, QWidget, QPushButton
from PyQt5.QtCore import pyqtSlot

In the initUI() method, add these lines of code:


button = QPushButton('PyQt5 button', self)
button.setToolTip('This is an example button')
button.move(100,70)

QPushButton creates the widget, the first argument is text on the button.
The method setToolTip shows the message when the user points the mouse on the button.
Finally the button is moved to the coordinates x=100,y=70.
We need to create a method for a button click:


@pyqtSlot()
def on_click(self):
print('PyQt5 button click')

Add connect the method to the click with:


button.clicked.connect(self.on_click)

Final PyQt5 button code:


import sys
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import pyqtSlot

class App(QWidget):

def __init__(self):
super().__init__()
self.title = 'PyQt5 button - pythonspot.com'
self.left = 10
self.top = 10
self.width = 320
self.height = 200
self.initUI()

def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)

button = QPushButton('PyQt5 button', self)
button.setToolTip('This is an example button')
button.move(100,70)
button.clicked.connect(self.on_click)

self.show()

@pyqtSlot()
def on_click(self):
print('PyQt5 button click')

if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())

If you are new to programming Python PyQt, I highly recommend this book.

pyqt5-button

Screenshot of PyQt5 button example above.

Download PyQT5 Examples

PyQt5 signals and slots

Graphical applications (GUI) are event-driven, unlike console or terminal applications. A users action like clicks a button or selecting an item in a list is called an event.

If an event takes place, each PyQt5 widget can emit a signal. A signal does not execute any action, that is done by a slot.

Related course:
Create GUI Apps with PyQt5

Signals and slot introduction
Consider this example:


button.clicked.connect(self.slot_method)

The button click (signal) is connected to the action (slot). In this example, the method slot_method will be called if the signal emits.

This principle of connecting slots methods or function to a widget, applies to all widgets,


widget.signal.connect(slot_method)

or we can explicitly define the signal:


QtCore.QObject.connect(widget, QtCore.SIGNAL(‘signalname’), slot_function)

PyQt supports many type of signals, not just clicks.

Example
We can create a method (slot) that is connected to a widget. A slot is any callable function or method.

pyqt button click

On running the application, we can click the button to execute the action (slot).


from PyQt5.QtWidgets import (QApplication, QComboBox, QDialog,
QDialogButtonBox, QFormLayout, QGridLayout, QGroupBox, QHBoxLayout,
QLabel, QLineEdit, QMenu, QMenuBar, QPushButton, QSpinBox, QTextEdit,
QVBoxLayout)

import sys

class Dialog(QDialog):

def slot_method(self):
print('slot method called.')

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

button=QPushButton("Click")
button.clicked.connect(self.slot_method)

mainLayout = QVBoxLayout()
mainLayout.addWidget(button)

self.setLayout(mainLayout)
self.setWindowTitle("Button Example - pythonspot.com")

if __name__ == '__main__':
app = QApplication(sys.argv)
dialog = Dialog()
sys.exit(dialog.exec_())

If you are new to programming Python PyQt, I highly recommend this book.

Download PyQT5 Examples

PyQt5 messagebox

In this article you will learn how to create a PyQt5 messagebox:

pyqt5-messagebox

To show a messagebox we need to import QMessageBox.


from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QMessageBox

We use the method QMessageBox.question() to display the messagebox.

Related course: Create GUI Apps with PyQt5

PyQt5 messagebox code
Copy the code below to display a messagebox.


import sys
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QMessageBox
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import pyqtSlot

class App(QWidget):

def __init__(self):
super().__init__()
self.title = 'PyQt5 messagebox - pythonspot.com'
self.left = 10
self.top = 10
self.width = 320
self.height = 200
self.initUI()

def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)

buttonReply = QMessageBox.question(self, 'PyQt5 message', "Do you like PyQt5?", QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
if buttonReply == QMessageBox.Yes:
print('Yes clicked.')
else:
print('No clicked.')

self.show()

if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())

More buttons for a messagebox
Take into account we use QMessageBox.Yes and QMessageBox.No. We can easily add other options:


buttonReply = QMessageBox.question(self, 'PyQt5 message', "Do you want to save?", QMessageBox.Yes | QMessageBox.No | QMessageBox.Cancel, QMessageBox.Cancel)
print(int(buttonReply))
if buttonReply == QMessageBox.Yes:
print('Yes clicked.')
if buttonReply == QMessageBox.No:
print('No clicked.')
if buttonReply == QMessageBox.Cancel:
print('Cancel')

The available buttons are:

Overview
QMessageBox.Cancel QMessageBox.Ok QMessageBox.Help
QMessageBox.Open QMessageBox.Save QMessageBox.SaveAll
QMessageBox.Discard QMessageBox.Close QMessageBox.Apply
QMessageBox.Reset QMessageBox.Yes QMessageBox.YesToAll
QMessageBox.No QMessageBox.NoToAll QMessageBox.NoButton
QMessageBox.RestoreDefaults QMessageBox.Abort QMessageBox.Retry
QMessageBox.Ignore

If you are new to programming Python PyQt, I highly recommend this book.

Download PyQT5 Examples

PyQt5 textbox example

In this article you will learn how to use a textbox in PyQt5. The widget is called QLineEdit and has the methods setText() to set the textbox value and text() to get the value.

We can set the size of the textbox using the resize(width,height) method. The position can be set using the move(x,y) method or using a grid layout.

Related course:

PyQt5 textbox
Creation of the textbox is fairly straightforward:


self.textbox = QLineEdit(self)
self.textbox.move(20, 20)
self.textbox.resize(280,40)

pyqt5-QLineEdit

PyQt5 textbox example

The example below creates a window with a textbox.


import sys
from PyQt5.QtWidgets import QMainWindow, QApplication, QWidget, QPushButton, QAction, QLineEdit, QMessageBox
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import pyqtSlot

class App(QMainWindow):

def __init__(self):
super().__init__()
self.title = 'PyQt5 textbox - pythonspot.com'
self.left = 10
self.top = 10
self.width = 400
self.height = 140
self.initUI()

def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)

# Create textbox
self.textbox = QLineEdit(self)
self.textbox.move(20, 20)
self.textbox.resize(280,40)

# Create a button in the window
self.button = QPushButton('Show text', self)
self.button.move(20,80)

# connect button to function on_click
self.button.clicked.connect(self.on_click)
self.show()

@pyqtSlot()
def on_click(self):
textboxValue = self.textbox.text()
QMessageBox.question(self, 'Message - pythonspot.com', "You typed: " + textboxValue, QMessageBox.Ok, QMessageBox.Ok)
self.textbox.setText("")

if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())

If you are new to programming Python PyQt, I highly recommend this book.

Download PyQT Code (Bulk Collection)

PyQt5 absolute position

PyQt5 supports several layout methods such as grid layouts, horzontal layous and absolute positioning. The layout you should pick depends on your preference and type of application.

Related course:
Create GUI Apps with PyQt5

PyQt5 absolute positioning


Absolute positioning gives you total control over the widget positions but you have to explicitly define every widget location.

Widgets can be added on an absolute position using the move(x,y) method.

pyqt5-absolute-position PyQt5 absolute positioning

PyQt5 widget positioning example


The example below puts widgets on the absolute positions using the move() method.
They are added to a PyQT5 window (QMainWindow) which has some properties set in initUI().


import sys
from PyQt5.QtWidgets import QApplication, QWidget, QMainWindow, QLabel
from PyQt5.QtGui import QIcon

class App(QMainWindow):

def __init__(self):
super().__init__()
self.title = 'PyQt absolute positioning - pythonspot.com'
self.left = 10
self.top = 10
self.width = 440
self.height = 280
self.initUI()

def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)

label = QLabel('Python', self)
label.move(50,50)

label2 = QLabel('PyQt5', self)
label2.move(100,100)

label3 = QLabel('Examples', self)
label3.move(150,150)

label4 = QLabel('pytonspot.com', self)
label4.move(200,200)

self.show()

if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())

If you are new to programming Python PyQt, I highly recommend this book.

Download PyQT5 Examples

PyQt5 menu

To create a menu for a PyQt5 program we need to use a QMainWindow.
This type of menu is visible in many applications and shows right below the window bar. It usually has a file and edit sub menu.

Related course:
Create GUI Apps with PyQt5

The top menu can be created with the method menuBar().
Sub menus are added with addMenu(name)
Example:


mainMenu = self.menuBar()
fileMenu = mainMenu.addMenu('File')
editMenu = mainMenu.addMenu('Edit')
viewMenu = mainMenu.addMenu('View')
searchMenu = mainMenu.addMenu('Search')
toolsMenu = mainMenu.addMenu('Tools')
helpMenu = mainMenu.addMenu('Help')

Individual buttons can be added to the menus like this:


exitButton = QAction(QIcon('exit24.png'), 'Exit', self)
exitButton.setShortcut('Ctrl+Q')
exitButton.setStatusTip('Exit application')
exitButton.triggered.connect(self.close)
fileMenu.addAction(exitButton)

PyQt5 menu example

Full code:


import sys
from PyQt5.QtWidgets import QMainWindow, QApplication, QWidget, QPushButton, QAction
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import pyqtSlot

class App(QMainWindow):

def __init__(self):
super().__init__()
self.title = 'PyQt5 menu - pythonspot.com'
self.left = 10
self.top = 10
self.width = 640
self.height = 400
self.initUI()

def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)

mainMenu = self.menuBar()
fileMenu = mainMenu.addMenu('File')
editMenu = mainMenu.addMenu('Edit')
viewMenu = mainMenu.addMenu('View')
searchMenu = mainMenu.addMenu('Search')
toolsMenu = mainMenu.addMenu('Tools')
helpMenu = mainMenu.addMenu('Help')

exitButton = QAction(QIcon('exit24.png'), 'Exit', self)
exitButton.setShortcut('Ctrl+Q')
exitButton.setStatusTip('Exit application')
exitButton.triggered.connect(self.close)
fileMenu.addAction(exitButton)

self.show()

if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())

Result:
pyqt5-menu

If you are new to programming Python PyQt, I highly recommend this book.

Download PyQT5 Examples

PyQt5 table

In this article you will learn how to use tables with PyQt5. You can add one or more tables to any PyQt application or window.

Tables can have multiple rows and columns. This can be specified with setRowCount() and setColumnCount().

PyQt5 table

To add a table, you will need to import QTableWidget and QTableWidgetItem.

Related course:

Example


from PyQt5.QtWidgets import QTableWidget,QTableWidgetItem

A table is created with:


self.tableWidget = QTableWidget()

# set row count
self.tableWidget.setRowCount(4)

# set column count
self.tableWidget.setColumnCount(2)

To add individual cells:


self.tableWidget.setItem(X,Y, QTableWidgetItem("TEXT"))

PyQt5 table example
The full PyQt5 table code is below:


import sys
from PyQt5.QtWidgets import QMainWindow, QApplication, QWidget, QAction, QTableWidget,QTableWidgetItem,QVBoxLayout
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import pyqtSlot

class App(QWidget):

def __init__(self):
super().__init__()
self.title = 'PyQt5 table - pythonspot.com'
self.left = 0
self.top = 0
self.width = 300
self.height = 200
self.initUI()

def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)

self.createTable()

# Add box layout, add table to box layout and add box layout to widget
self.layout = QVBoxLayout()
self.layout.addWidget(self.tableWidget)
self.setLayout(self.layout)

# Show widget
self.show()

def createTable(self):
# Create table
self.tableWidget = QTableWidget()
self.tableWidget.setRowCount(4)
self.tableWidget.setColumnCount(2)
self.tableWidget.setItem(0,0, QTableWidgetItem("Cell (1,1)"))
self.tableWidget.setItem(0,1, QTableWidgetItem("Cell (1,2)"))
self.tableWidget.setItem(1,0, QTableWidgetItem("Cell (2,1)"))
self.tableWidget.setItem(1,1, QTableWidgetItem("Cell (2,2)"))
self.tableWidget.setItem(2,0, QTableWidgetItem("Cell (3,1)"))
self.tableWidget.setItem(2,1, QTableWidgetItem("Cell (3,2)"))
self.tableWidget.setItem(3,0, QTableWidgetItem("Cell (4,1)"))
self.tableWidget.setItem(3,1, QTableWidgetItem("Cell (4,2)"))
self.tableWidget.move(0,0)

# table selection change
self.tableWidget.doubleClicked.connect(self.on_click)

@pyqtSlot()
def on_click(self):
print("\n")
for currentQTableWidgetItem in self.tableWidget.selectedItems():
print(currentQTableWidgetItem.row(), currentQTableWidgetItem.column(), currentQTableWidgetItem.text())

if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())

If you are new to programming Python PyQt, I highly recommend this book.

Download PyQT5 Examples

PyQt5 tabs

In this article you will learn to use tabs with PyQt5. We’ll show the full code first, then explain. PyQt5 has a widget to create tabs known as QTabWidget. The QTabWidget can contain tabs (QWidgets), which have widgets on them such as labels, buttons, images etcetera.

pyqt5-tabs

Related course:

PyQt5 tabs example
Full PyQt5 tabs example:


import sys
from PyQt5.QtWidgets import QMainWindow, QApplication, QPushButton, QWidget, QAction, QTabWidget,QVBoxLayout
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import pyqtSlot

class App(QMainWindow):

def __init__(self):
super().__init__()
self.title = 'PyQt5 tabs - pythonspot.com'
self.left = 0
self.top = 0
self.width = 300
self.height = 200
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)

self.table_widget = MyTableWidget(self)
self.setCentralWidget(self.table_widget)

self.show()

class MyTableWidget(QWidget):

def __init__(self, parent):
super(QWidget, self).__init__(parent)
self.layout = QVBoxLayout(self)

# Initialize tab screen
self.tabs = QTabWidget()
self.tab1 = QWidget()
self.tab2 = QWidget()
self.tabs.resize(300,200)

# Add tabs
self.tabs.addTab(self.tab1,"Tab 1")
self.tabs.addTab(self.tab2,"Tab 2")

# Create first tab
self.tab1.layout = QVBoxLayout(self)
self.pushButton1 = QPushButton("PyQt5 button")
self.tab1.layout.addWidget(self.pushButton1)
self.tab1.setLayout(self.tab1.layout)

# Add tabs to widget
self.layout.addWidget(self.tabs)
self.setLayout(self.layout)

@pyqtSlot()
def on_click(self):
print("\n")
for currentQTableWidgetItem in self.tableWidget.selectedItems():
print(currentQTableWidgetItem.row(), currentQTableWidgetItem.column(), currentQTableWidgetItem.text())

if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())

Explanation:

To add a table to a window, we create a new class:


class MyTableWidget(QWidget)

We initialize the tab screen by creating a QTabWidget and two QWidgets for tabs.


self.tabs = QTabWidget()
self.tab1 = QWidget()
self.tab2 = QWidget()
self.tabs.resize(300,200)

We then add these tabs to the tab widget:


self.tabs.addTab(self.tab1,"Tab 1")
self.tabs.addTab(self.tab2,"Tab 2")

The contents of a tab are created using:


self.tab1.layout = QVBoxLayout(self)
self.pushButton1 = QPushButton("PyQt5 button")
self.tab1.layout.addWidget(self.pushButton1)
self.tab1.setLayout(self.tab1.layout)

Finally we add the tabs to the widget:


self.layout.addWidget(self.tabs)
self.setLayout(self.layout)

don’t forget the to add your custom tab widget to the window:


self.table_widget = MyTableWidget(self)
self.setCentralWidget(self.table_widget)

If you are new to programming Python PyQt, I highly recommend this book.

Download PyQT5 Examples

PyQt5 horizontal layout

A window can contain widgets (buttons, text field, image and others). Widgets are frequently added to a layout. A horizontal layout can be used to (dynamically) add widgets in horizontal direction.

In this article we’ll show you how to add buttons in the horizontal direction using a horizontal layout.

pyqt5-horizontal-layout

Related course:

Horizontal layout example
We will show the whole code and then explain.


import sys
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QHBoxLayout, QGroupBox, QDialog, QVBoxLayout
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import pyqtSlot

class App(QDialog):

def __init__(self):
super().__init__()
self.title = 'PyQt5 layout - pythonspot.com'
self.left = 10
self.top = 10
self.width = 320
self.height = 100
self.initUI()

def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)

self.createHorizontalLayout()

windowLayout = QVBoxLayout()
windowLayout.addWidget(self.horizontalGroupBox)
self.setLayout(windowLayout)

self.show()

def createHorizontalLayout(self):
self.horizontalGroupBox = QGroupBox("What is your favorite color?")
layout = QHBoxLayout()

buttonBlue = QPushButton('Blue', self)
buttonBlue.clicked.connect(self.on_click)
layout.addWidget(buttonBlue)

buttonRed = QPushButton('Red', self)
buttonRed.clicked.connect(self.on_click)
layout.addWidget(buttonRed)

buttonGreen = QPushButton('Green', self)
buttonGreen.clicked.connect(self.on_click)
layout.addWidget(buttonGreen)

self.horizontalGroupBox.setLayout(layout)

@pyqtSlot()
def on_click(self):
print('PyQt5 button click')

if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())

Explanation

We start by calling the method self.createHorizontalLayout() inside the initUI() method.
Inside the method we create a box with a title and a horizontal layout:


self.horizontalGroupBox = QGroupBox("What is your favorite color?")
layout = QHBoxLayout()

We create widgets (in this example QPushButtons) and add them to the layout one by one:


buttonBlue = QPushButton('Blue', self)
buttonBlue.clicked.connect(self.on_click)
layout.addWidget(buttonBlue)

We set the title-box to contain the horizontal layout:


self.horizontalGroupBox.setLayout(layout)

In the initUI method we add it to the window:


windowLayout = QVBoxLayout()
windowLayout.addWidget(self.horizontalGroupBox)
self.setLayout(windowLayout)

If you are new to programming Python PyQt, I highly recommend this book.

Download PyQT5 Examples

PyQt5 grid layout

PyQt5 supports a grid layout, which is named QGridLayout. Widgets can be added to a grid in both the horizontal and vertical direction. An example of a grid layout with widgets is shown below:

pyqt-grid-layout

Related course:

PyQt5 grid layout example:
The example below creates the grid:


import sys
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QHBoxLayout, QGroupBox, QDialog, QVBoxLayout, QGridLayout
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import pyqtSlot

class App(QDialog):

def __init__(self):
super().__init__()
self.title = 'PyQt5 layout - pythonspot.com'
self.left = 10
self.top = 10
self.width = 320
self.height = 100
self.initUI()

def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)

self.createGridLayout()

windowLayout = QVBoxLayout()
windowLayout.addWidget(self.horizontalGroupBox)
self.setLayout(windowLayout)

self.show()

def createGridLayout(self):
self.horizontalGroupBox = QGroupBox("Grid")
layout = QGridLayout()
layout.setColumnStretch(1, 4)
layout.setColumnStretch(2, 4)

layout.addWidget(QPushButton('1'),0,0)
layout.addWidget(QPushButton('2'),0,1)
layout.addWidget(QPushButton('3'),0,2)
layout.addWidget(QPushButton('4'),1,0)
layout.addWidget(QPushButton('5'),1,1)
layout.addWidget(QPushButton('6'),1,2)
layout.addWidget(QPushButton('7'),2,0)
layout.addWidget(QPushButton('8'),2,1)
layout.addWidget(QPushButton('9'),2,2)

self.horizontalGroupBox.setLayout(layout)

if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())

Explanation

We import the gridlayout and others with:


from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QHBoxLayout, QGroupBox, QDialog, QVBoxLayout, QGridLayout

In the method createGridLayout() we create the grid with a title and set the size.


def createGridLayout(self):
self.horizontalGroupBox = QGroupBox("Grid")
layout = QGridLayout()
layout.setColumnStretch(1, 4)
layout.setColumnStretch(2, 4)

Widgets are added using


layout.addWidget(Widget,X,Y)

Finally we set the layout.

If you are new to programming Python PyQt, I highly recommend this book.

Download PyQT5 Examples

PyQT5 input dialog

PyQt5 supports several input dialogs, to use them import QInputDialog.


from PyQt5.QtWidgets import QApplication, QWidget, QInputDialog, QLineEdit

An overview of PyQt5 input dialogs:

pyqt5-input-dialog

Related course:

Get integer
Get an integer with QInputDialog.getInt():


def getInteger(self):
i, okPressed = QInputDialog.getInt(self, "Get integer","Percentage:", 28, 0, 100, 1)
if okPressed:
print(i)

Parameters in order: self, window title, label (before input box), default value, minimum, maximum and step size.

Get double
Get a double with QInputDialog.getDouble():


def getDouble(self):
d, okPressed = QInputDialog.getDouble(self, "Get double","Value:", 10.05, 0, 100, 10)
if okPressed:
print(d)

The last parameter (10) is the number of decimals behind the comma.

Get item/choice
Get an item from a dropdown box:


def getChoice(self):
items = ("Red","Blue","Green")
item, okPressed = QInputDialog.getItem(self, "Get item","Color:", items, 0, False)
if okPressed and item:
print(item)

Get a string
Get a string using QInputDialog.getText()


def getText(self):
text, okPressed = QInputDialog.getText(self, "Get text","Your name:", QLineEdit.Normal, "")
if okPressed and text != '':
print(text)

Example all PyQt5 input dialogs
Complete example below:


import sys
from PyQt5.QtWidgets import QApplication, QWidget, QInputDialog, QLineEdit
from PyQt5.QtGui import QIcon

class App(QWidget):

def __init__(self):
super().__init__()
self.title = 'PyQt5 input dialogs - pythonspot.com'
self.left = 10
self.top = 10
self.width = 640
self.height = 480
self.initUI()

def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)

self.getInteger()
self.getText()
self.getDouble()
self.getChoice()

self.show()

def getInteger(self):
i, okPressed = QInputDialog.getInt(self, "Get integer","Percentage:", 28, 0, 100, 1)
if okPressed:
print(i)

def getDouble(self):
d, okPressed = QInputDialog.getDouble(self, "Get double","Value:", 10.50, 0, 100, 10)
if okPressed:
print( d)

def getChoice(self):
items = ("Red","Blue","Green")
item, okPressed = QInputDialog.getItem(self, "Get item","Color:", items, 0, False)
if ok and item:
print(item)

def getText(self):
text, okPressed = QInputDialog.getText(self, "Get text","Your name:", QLineEdit.Normal, "")
if okPressed and text != '':
print(text)

if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())

If you are new to programming Python PyQt, I highly recommend this book.

Download PyQT5 Examples

PyQt5 file dialog

PyQt5 supports (native) file dialogs: open file, open files and save file. By calling the functions included in PyQt5 you get the default file dialog, you don’t have to recreate these dialogs from scratch.

Importing QFileDialog is required.

Related course:

File dialog example
The methods used are QFileDialog.getOpenFileName(), QFileDialog.getOpenFileNames(), QFileDialog.getSaveFileName(). The method parameters let you specify the default directory, filetypes and the default filename.

pyqt5-open-file-dialog

The code below will show all file dialogs:


import sys
from PyQt5.QtWidgets import QApplication, QWidget, QInputDialog, QLineEdit, QFileDialog
from PyQt5.QtGui import QIcon

class App(QWidget):

def __init__(self):
super().__init__()
self.title = 'PyQt5 file dialogs - pythonspot.com'
self.left = 10
self.top = 10
self.width = 640
self.height = 480
self.initUI()

def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)

self.openFileNameDialog()
self.openFileNamesDialog()
self.saveFileDialog()

self.show()

def openFileNameDialog(self):
options = QFileDialog.Options()
options |= QFileDialog.DontUseNativeDialog
fileName, _ = QFileDialog.getOpenFileName(self,"QFileDialog.getOpenFileName()", "","All Files (*);;Python Files (*.py)", options=options)
if fileName:
print(fileName)

def openFileNamesDialog(self):
options = QFileDialog.Options()
options |= QFileDialog.DontUseNativeDialog
files, _ = QFileDialog.getOpenFileNames(self,"QFileDialog.getOpenFileNames()", "","All Files (*);;Python Files (*.py)", options=options)
if files:
print(files)

def saveFileDialog(self):
options = QFileDialog.Options()
options |= QFileDialog.DontUseNativeDialog
fileName, _ = QFileDialog.getSaveFileName(self,"QFileDialog.getSaveFileName()","","All Files (*);;Text Files (*.txt)", options=options)
if fileName:
print(fileName)

if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())

If you are new to programming Python PyQt, I highly recommend this book.

Download PyQT5 Examples

PyQt5 image

PyQt5 (and Qt) support images by default. In this article we’ll show you how to add an image to a window. An image can be loaded using the QPixmap class.

Related course:

PyQt5 image introduction
Adding an image to a PyQt5 window is as simple as creating a label and adding an image to that label.


label = QLabel(self)
pixmap = QPixmap('image.jpeg')
label.setPixmap(pixmap)

# Optional, resize window to image size
self.resize(pixmap.width(),pixmap.height())

These are the required imports:


from PyQt5.QtWidgets import QApplication, QWidget, QLabel
from PyQt5.QtGui import QIcon, QPixmap

pyqt5 qpixmap

PyQt5 load image (QPixmap)

Copy the code below and run it. The image should be in the same directory as your program.


import sys
from PyQt5.QtWidgets import QApplication, QWidget, QLabel
from PyQt5.QtGui import QIcon, QPixmap

class App(QWidget):

def __init__(self):
super().__init__()
self.title = 'PyQt5 image - pythonspot.com'
self.left = 10
self.top = 10
self.width = 640
self.height = 480
self.initUI()

def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)

# Create widget
label = QLabel(self)
pixmap = QPixmap('image.jpeg')
label.setPixmap(pixmap)
self.resize(pixmap.width(),pixmap.height())

self.show()

if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())

If you are new to programming Python PyQt, I highly recommend this book.

Download PyQT5 Examples

PyQt5 pixels

You can paint in a PyQt5 window using the QPainter widget. This widget supports adding pixels (dots) inside of the widget, unlike the other widgets. In this article we’ll explain how to use the QPainter widget with Python.

To use the widget in Qt5 we import PyQt5.QtGui. This also contains other classes like QPen and QColor.

Related course:

QPainter Widget Example
We set the window background using:


# Set window background color
self.setAutoFillBackground(True)
p = self.palette()
p.setColor(self.backgroundRole(), Qt.white)
self.setPalette(p)

Pixels are added using the drawPoint(x, y) method.

qpainterPyQt5 qpainter example

PyQt5 QPainter example
The example below paints pixels in the QPainter widget:


import sys
from PyQt5.QtWidgets import QApplication, QWidget, QMainWindow, QLabel
from PyQt5.QtGui import QPainter, QColor, QPen
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import Qt
import random

class App(QMainWindow):

def __init__(self):
super().__init__()
self.title = 'PyQt paint - pythonspot.com'
self.left = 10
self.top = 10
self.width = 440
self.height = 280
self.initUI()

def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)

# Set window background color
self.setAutoFillBackground(True)
p = self.palette()
p.setColor(self.backgroundRole(), Qt.white)
self.setPalette(p)

# Add paint widget and paint
self.m = PaintWidget(self)
self.m.move(0,0)
self.m.resize(self.width,self.height)

self.show()

class PaintWidget(QWidget):
def paintEvent(self, event):
qp = QPainter(self)

qp.setPen(Qt.black)
size = self.size()

for i in range(1024):
x = random.randint(1, size.width()-1)
y = random.randint(1, size.height()-1)
qp.drawPoint(x, y)

if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())

If you are new to programming Python PyQt, I highly recommend this book.

Download PyQT5 Examples

PyQT5 color dialog

PyQt5 supports a color picker known as QColorDialog. This dialog is a typical dialog that you would see in a paint or graphics program.

To get a color from PyQt5 dialog simply call:


color = QColorDialog.getColor()

QColorDialog A color dialog using PyQt5

Related course:

PyQt5 color dialog example
The example below opens a QColorDialog after clicking the button, and returns the selected color.


import sys
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QColorDialog
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import pyqtSlot
from PyQt5.QtGui import QColor

class App(QWidget):

def __init__(self):
super().__init__()
self.title = 'PyQt5 color dialog - pythonspot.com'
self.left = 10
self.top = 10
self.width = 320
self.height = 200
self.initUI()

def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)

button = QPushButton('Open color dialog', self)
button.setToolTip('Opens color dialog')
button.move(10,10)
button.clicked.connect(self.on_click)

self.show()

@pyqtSlot()
def on_click(self):
openColorDialog(self)

def openColorDialog(self):
color = QColorDialog.getColor()

if color.isValid():
print(color.name())

if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())

If you are new to programming Python PyQt, I highly recommend this book.

Download PyQT5 Examples

PyQt5 drag and drop

Like any modern GUI toolkit, PyQt supports drag and drop. A widget parameter must be set using the setDragEnabled(True) method call. A custom widget should then be set to accept a drop with setAcceptDrops(True).

pyqt-drag-and-drop Drag and drop using PyQt5

Related course:
Create GUI Apps with PyQt5

PyQt5 drag and drop example


Drag text from the input field to the label, the label will update its text.


import sys
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QLineEdit, QLabel
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import pyqtSlot

class App(QWidget):

def __init__(self):
super().__init__()
self.title = 'PyQt5 drag and drop - pythonspot.com'
self.left = 10
self.top = 10
self.width = 320
self.height = 60
self.initUI()

def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)

editBox = QLineEdit('Drag this', self)
editBox.setDragEnabled(True)
editBox.move(10, 10)
editBox.resize(100,32)

button = CustomLabel('Drop here.', self)
button.move(130,15)

self.show()

@pyqtSlot()
def on_click(self):
print('PyQt5 button click')

class CustomLabel(QLabel):

def __init__(self, title, parent):
super().__init__(title, parent)
self.setAcceptDrops(True)

def dragEnterEvent(self, e):
if e.mimeData().hasFormat('text/plain'):
e.accept()
else:
e.ignore()

def dropEvent(self, e):
self.setText(e.mimeData().text())

if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())

If you are new to programming Python PyQt, I highly recommend this book.

The textbox is created with the call QLineEdit(). A custom class (CustomLabel) is created that accepts drag and drop. Both events are defined as methods and have their logic executed if the event occurs.

Download PyQT5 Examples

PyQt5 font dialog

PyQt5 comes with a font dialog that you may have seen in a text editor. This is the typical dialog where you can select font, font size, font style and so on. Of course the look and feel depends on the operating system.

To open this dialog import QFontDialog call:

QFontDialog.getFont()

To use it, import QFontDialog from QtWidgets like this:

from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QFontDialog

Related course:

PyQt5 font dialog

The example below opens a font dialog on a button event, the selected font (font family including size) will be returned as a string.

pyqt-font-dialog Font Dialog using PyQt5

Opening a font dialog is as simple as

def openFontDialog(self):
font, ok = QFontDialog.getFont()
if ok:
print(font.toString())

A full code example is shown below


import sys
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QFontDialog
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import pyqtSlot

class App(QWidget):

def __init__(self):
super().__init__()
self.title = 'PyQt5 font dialog - pythonspot.com'
self.left = 10
self.top = 10
self.width = 320
self.height = 200
self.initUI()

def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)

button = QPushButton('Open PyQt5 Font Dialog', self)
button.setToolTip('font dialog')
button.move(50,50)
button.clicked.connect(self.on_click)

self.show()

@pyqtSlot()
def on_click(self):
print('PyQt5 button click')
openFontDialog(self)

def openFontDialog(self):
font, ok = QFontDialog.getFont()
if ok:
print(font.toString())

if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())

If you are new to programming Python PyQt, I highly recommend this book.

Download PyQT5 Examples

PyQt5 colors

Colors in PyQt5 are defined using the method QColor(r, g, b). All colors on the screen are a combination of the red, green and blue values. Every color value should be in the range 0..255.
In a QPainter widget you can pass a color to the setBrush method.

QColor QColor example

Related course:
Create GUI Apps with PyQt5

PyQt5 color example:
This example draws a variety of colors in a QPainter widget using the setBrush and QColor methods.


import sys
from PyQt5.QtWidgets import QApplication, QWidget, QMainWindow, QLabel
from PyQt5.QtGui import QPainter, QColor, QPen
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import Qt
import random

class App(QMainWindow):

def __init__(self):
super().__init__()
self.title = 'PyQt rectangle colors - pythonspot.com'
self.left = 10
self.top = 10
self.width = 440
self.height = 280
self.initUI()

def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)

# Set window background color
self.setAutoFillBackground(True)
p = self.palette()
p.setColor(self.backgroundRole(), Qt.white)
self.setPalette(p)

# Add paint widget and paint
self.m = PaintWidget(self)
self.m.move(0,0)
self.m.resize(self.width,self.height)

self.show()

class PaintWidget(QWidget):
def paintEvent(self, event):
qp = QPainter(self)

qp.setPen(Qt.black)
size = self.size()

# Colored rectangles
qp.setBrush(QColor(200, 0, 0))
qp.drawRect(0, 0, 100, 100)

qp.setBrush(QColor(0, 200, 0))
qp.drawRect(100, 0, 100, 100)

qp.setBrush(QColor(0, 0, 200))
qp.drawRect(200, 0, 100, 100)

# Color Effect
for i in range(0,100):
qp.setBrush(QColor(i*10, 0, 0))
qp.drawRect(10*i, 100, 10, 32)

qp.setBrush(QColor(i*10, i*10, 0))
qp.drawRect(10*i, 100+32, 10, 32)

qp.setBrush(QColor(i*2, i*10, i*1))
qp.drawRect(10*i, 100+64, 10, 32)

if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())

Download PyQT5 Examples

PyQt5 Matplotlib

Matplotlib plots can be included in a PyQt5 application.
Several imports need to be added:


from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
import matplotlib.pyplot as plt

We create a widget called PlotCanvas that includes the Matplotlib plot.

pyqt5-matplotlib Matplot plot in PyQt5 window

PyQt5 Matplotlib example
The example below embeds a matplotlib plot in a PyQt5 window.


import sys

from PyQt5.QtWidgets import QApplication, QMainWindow, QMenu, QVBoxLayout, QSizePolicy, QMessageBox, QWidget, QPushButton
from PyQt5.QtGui import QIcon


from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
import matplotlib.pyplot as plt

import random

class App(QMainWindow):

def __init__(self):
super().__init__()
self.left = 10
self.top = 10
self.title = 'PyQt5 matplotlib example - pythonspot.com'
self.width = 640
self.height = 400
self.initUI()

def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)

m = PlotCanvas(self, width=5, height=4)
m.move(0,0)

button = QPushButton('PyQt5 button', self)
button.setToolTip('This s an example button')
button.move(500,0)
button.resize(140,100)

self.show()


class PlotCanvas(FigureCanvas):

def __init__(self, parent=None, width=5, height=4, dpi=100):
fig = Figure(figsize=(width, height), dpi=dpi)
self.axes = fig.add_subplot(111)

FigureCanvas.__init__(self, fig)
self.setParent(parent)

FigureCanvas.setSizePolicy(self,
QSizePolicy.Expanding,
QSizePolicy.Expanding)
FigureCanvas.updateGeometry(self)
self.plot()


def plot(self):
data = [random.random() for i in range(25)]
ax = self.figure.add_subplot(111)
ax.plot(data, 'r-')
ax.set_title('PyQt Matplotlib Example')
self.draw()

if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())

Download PyQT5 Examples

PyQt5 Treeview

PyQt5 (python with qt5 bindings) supports a tree view widget (class QTreeView). In this article we will show how to use the widget.

treeview pyqt5

The image shows a QTreeView widget with data inside it.

Related course:
Create GUI Apps with PyQt5

PyQt5 Treeview Example


The code below will create a treeview using the QTreeView class (Run using Python 3). Data is added to the treeview by code. Explanation of the code is below the code block.


#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import sys
from PyQt5.QtGui import QIcon

from PyQt5.QtCore import (QDate, QDateTime, QRegExp, QSortFilterProxyModel, Qt,
QTime)
from PyQt5.QtGui import QStandardItemModel
from PyQt5.QtWidgets import (QApplication, QCheckBox, QComboBox, QGridLayout,
QGroupBox, QHBoxLayout, QLabel, QLineEdit, QTreeView, QVBoxLayout,
QWidget)

class App(QWidget):

FROM, SUBJECT, DATE = range(3)

def __init__(self):
super().__init__()
self.title = 'PyQt5 Treeview Example - pythonspot.com'
self.left = 10
self.top = 10
self.width = 640
self.height = 240
self.initUI()

def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)

self.dataGroupBox = QGroupBox("Inbox")
self.dataView = QTreeView()
self.dataView.setRootIsDecorated(False)
self.dataView.setAlternatingRowColors(True)

dataLayout = QHBoxLayout()
dataLayout.addWidget(self.dataView)
self.dataGroupBox.setLayout(dataLayout)

model = self.createMailModel(self)
self.dataView.setModel(model)
self.addMail(model, '[email protected]', 'Your Github Donation','03/25/2017 02:05 PM')
self.addMail(model, '[email protected]', 'Github Projects','02/02/2017 03:05 PM')
self.addMail(model, '[email protected]', 'Your Phone Bill','01/01/2017 04:05 PM')

mainLayout = QVBoxLayout()
mainLayout.addWidget(self.dataGroupBox)
self.setLayout(mainLayout)

self.show()

def createMailModel(self,parent):
model = QStandardItemModel(0, 3, parent)
model.setHeaderData(self.FROM, Qt.Horizontal, "From")
model.setHeaderData(self.SUBJECT, Qt.Horizontal, "Subject")
model.setHeaderData(self.DATE, Qt.Horizontal, "Date")
return model

def addMail(self,model, mailFrom, subject, date):
model.insertRow(0)
model.setData(model.index(0, self.FROM), mailFrom)
model.setData(model.index(0, self.SUBJECT), subject)
model.setData(model.index(0, self.DATE), date)

if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())

If you are new to programming Python PyQt, I highly recommend this book.

Treeview Explanation


We create a new tree view object using the line:


self.dataView = QTreeView()

The view is set to have a model,


self.dataView.setModel(model)

Where model is


model = QStandardItemModel(0, 3, parent)
model.setHeaderData(self.FROM, Qt.Horizontal, "From")
model.setHeaderData(self.SUBJECT, Qt.Horizontal, "Subject")
model.setHeaderData(self.DATE, Qt.Horizontal, "Date")

Then we add data using:


model.insertRow(0)
model.setData(model.index(0, self.FROM), mailFrom)
model.setData(model.index(0, self.SUBJECT), subject)
model.setData(model.index(0, self.DATE), date)

Download PyQT5 Examples

PyQt5 Directory View

PyQt can show a directory structure using a QTreeView. For the treeview to show as a directory tree, we need to set its model to a QFileSystemModel instance. That is achieved by calling the setModel method for the tree instance.

We can set additional options on the tree object: sorting enabled (setSortingEnabled), animation and indention.

qt5 directory view

Related course:

Example
The code below will add the directory view (QTreeView combined with QFileSystemModel) to a grid window. A layout needs to be set for the widget to be seen.

The path is specified using the models setRootPath() method, where the parameter is the full path to the directory. By default its the root.


import sys
from PyQt5.QtWidgets import QApplication, QFileSystemModel, QTreeView, QWidget, QVBoxLayout
from PyQt5.QtGui import QIcon

class App(QWidget):

def __init__(self):
super().__init__()
self.title = 'PyQt5 file system view - pythonspot.com'
self.left = 10
self.top = 10
self.width = 640
self.height = 480
self.initUI()

def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)

self.model = QFileSystemModel()
self.model.setRootPath('')
self.tree = QTreeView()
self.tree.setModel(self.model)

self.tree.setAnimated(False)
self.tree.setIndentation(20)
self.tree.setSortingEnabled(True)

self.tree.setWindowTitle("Dir View")
self.tree.resize(640, 480)

windowLayout = QVBoxLayout()
windowLayout.addWidget(self.tree)
self.setLayout(windowLayout)

self.show()

if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())

If you are new to programming Python PyQt, I highly recommend this book.

Download PyQT5 Examples

PyQt5 Form Layout

A form can be created using the class QFormLayout. This is the easiest way to create a form where widgets (input) have descriptions (labels).

In this article we’ll show you how to create a form with pyqt.

form layout

Related course:

Form Layout Example
The Form Layout is created using the class QFormLayout. We can add rows to the form using the method addRow. The method is defined as


addRow(QWidget * label, QWidget * field)

We call the method using two widgets where the first is the label and the second the type of widget.


from PyQt5.QtWidgets import (QApplication, QComboBox, QDialog,
QDialogButtonBox, QFormLayout, QGridLayout, QGroupBox, QHBoxLayout,
QLabel, QLineEdit, QMenu, QMenuBar, QPushButton, QSpinBox, QTextEdit,
QVBoxLayout)

import sys

class Dialog(QDialog):
NumGridRows = 3
NumButtons = 4

def __init__(self):
super(Dialog, self).__init__()
self.createFormGroupBox()

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

mainLayout = QVBoxLayout()
mainLayout.addWidget(self.formGroupBox)
mainLayout.addWidget(buttonBox)
self.setLayout(mainLayout)

self.setWindowTitle("Form Layout - pythonspot.com")

def createFormGroupBox(self):
self.formGroupBox = QGroupBox("Form layout")
layout = QFormLayout()
layout.addRow(QLabel("Name:"), QLineEdit())
layout.addRow(QLabel("Country:"), QComboBox())
layout.addRow(QLabel("Age:"), QSpinBox())
self.formGroupBox.setLayout(layout)

if __name__ == '__main__':
app = QApplication(sys.argv)
dialog = Dialog()
sys.exit(dialog.exec_())

If you are new to programming Python PyQt, I highly recommend this book.

Download PyQT5 Examples

PyQt5 QBoxLayout

An instance of the QBoxLayout divides the given space into boxes, where each box is totally filled with one exact widget. It can add widgets in vertical or horizontal direction, where the choice of vertical or horizontal depends on type of class the object is instanced from.

The class QVBoxLayout adds widgets in vertical direction while the QHBoxLayout adds widgets in horizontal direction.

Related course:

QVboxLayout - Vertical layout
We can add widgets in vertical direction using the QVBoxLayout class. The QVBoxLayout class inherits from the QBoxLayout class.
qvboxlayout

In this example we add widgets (buttons) to a QVBoxLayout instance and we add the instance to the window.


from PyQt5.QtWidgets import (QApplication, QComboBox, QDialog,
QDialogButtonBox, QFormLayout, QGridLayout, QGroupBox, QHBoxLayout,
QLabel, QLineEdit, QMenu, QMenuBar, QPushButton, QSpinBox, QTextEdit,
QVBoxLayout)

import sys

class Dialog(QDialog):
NumGridRows = 3
NumButtons = 4

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

b1=QPushButton("Button1")
b2=QPushButton("Button2")
b3=QPushButton("Button3")
b4=QPushButton("Button4")

mainLayout = QVBoxLayout()
mainLayout.addWidget(b1)
mainLayout.addWidget(b2)
mainLayout.addWidget(b3)
mainLayout.addWidget(b4)

self.setLayout(mainLayout)
self.setWindowTitle("Form Layout - pythonspot.com")

if __name__ == '__main__':
app = QApplication(sys.argv)
dialog = Dialog()
sys.exit(dialog.exec_())

If you are new to programming Python PyQt, I highly recommend this book.

Download PyQT5 Examples

PyQt5 browser

QWebView Class Simplified QWebView class simplified

PyQt5 supports a widget that displays websites named QWebView.

QWebView uses the Webkit rendering engine
The web browser engine is used by Safari, App Store and many OS X applications.

The load() method opens the url (QUrl) in the argument. You can create a QUrl using: QUrl(url).

The show() method is required to display the widget.

Related course:

Installation


To use this widget you may need to install an additional package:


sudo apt-get install python3-pyqt5.qtwebkit

Read more about PyQt5.

PyQt5 webkit example


The example below loads a webpage in a PyQt5 window.


#!/usr/bin/env python

import sys
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtWebKit import *
from PyQt5.QtWebKitWidgets import *
from PyQt5.QtWidgets import QApplication, QWidget, QMainWindow

app = QApplication(sys.argv)

web = QWebView()
web.load(QUrl("https://pythonspot.com"))
web.show()

sys.exit(app.exec_())

pyqt5-webkit Webkit in PyQt5

Download PyQT5 Examples

PyQt5 webkit browser

QWebview inside a browser PyQt5 Webkit (QWebview) inside a browser

PyQt5 comes with a webkit webbrowser. Webkit is an open source web browser rendering engine that is used by Apple Safari and others. It was used in the older versions of Google Chrome, they have switched to the Blink rendering engine.

Related course:
Create GUI Apps with PyQt5

QWebView
The widget is called QWebView and webpages (HTML content) can be shown through this widget, local or live from the internet.

Download Example Code

Methods
The QWebView class comes with a lot of methods including:


  • back (self)

  • forward (self)

  • load (self, QUrl url)

  • reload (self)


More documentation on this class can be found on ics.uci.edu


#!/usr/bin/python

import PyQt5
from PyQt5.QtCore import QUrl
from PyQt5.QtWidgets import QApplication, QWidget
from PyQt5.QtWebKitWidgets import QWebView , QWebPage
from PyQt5.QtWebKit import QWebSettings
from PyQt5.QtNetwork import *
import sys
from optparse import OptionParser

class MyBrowser(QWebPage):
''' Settings for the browser.'''

def userAgentForUrl(self, url):
''' Returns a User Agent that will be seen by the website. '''
return "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36"

class Browser(QWebView):
def __init__(self):
# QWebView
self.view = QWebView.__init__(self)
#self.view.setPage(MyBrowser())
self.setWindowTitle('Loading...')
self.titleChanged.connect(self.adjustTitle)
#super(Browser).connect(self.ui.webView,QtCore.SIGNAL("titleChanged (const QString&)"), self.adjustTitle)

def load(self,url):
self.setUrl(QUrl(url))

def adjustTitle(self):
self.setWindowTitle(self.title())

def disableJS(self):
settings = QWebSettings.globalSettings()
settings.setAttribute(QWebSettings.JavascriptEnabled, False)

app = QApplication(sys.argv)
view = Browser()
view.showMaximized()
view.load("https://pythonspot.com")
app.exec_()

Related course:
Create GUI Apps with PyQt5

PyQt5 Wizard

A wizard is a screen you often see during installations, you have back and next buttons, and are guided through a process.

In PyQt5 these are called pages, every page can have some content. The buttons will guide you through these pages.

Related course:

Wizard Example
The code below creates a wizard in PyQt:


#!/usr/bin/env python

from PyQt5 import QtCore
from PyQt5 import QtGui
from PyQt5.QtCore import pyqtProperty
from PyQt5 import QtCore, QtWidgets

class QIComboBox(QtWidgets.QComboBox):
def __init__(self,parent=None):
super(QIComboBox, self).__init__(parent)


class MagicWizard(QtWidgets.QWizard):
def __init__(self, parent=None):
super(MagicWizard, self).__init__(parent)
self.addPage(Page1(self))
self.addPage(Page2(self))
self.setWindowTitle("PyQt5 Wizard Example - pythonspot.com")
self.resize(640,480)

class Page1(QtWidgets.QWizardPage):
def __init__(self, parent=None):
super(Page1, self).__init__(parent)
self.comboBox = QIComboBox(self)
self.comboBox.addItem("Python","/path/to/filename1")
self.comboBox.addItem("PyQt5","/path/to/filename2")
layout = QtWidgets.QVBoxLayout()
layout.addWidget(self.comboBox)
self.setLayout(layout)


class Page2(QtWidgets.QWizardPage):
def __init__(self, parent=None):
super(Page2, self).__init__(parent)
self.label1 = QtWidgets.QLabel()
self.label2 = QtWidgets.QLabel()
layout = QtWidgets.QVBoxLayout()
layout.addWidget(self.label1)
layout.addWidget(self.label2)
self.setLayout(layout)

def initializePage(self):
self.label1.setText("Example text")
self.label2.setText("Example text")

if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
wizard = MagicWizard()
wizard.show()
sys.exit(app.exec_())


Screenshot:

pyqt wizard

For every page you can add a new class, where inside the method initializePage you can set the widgets. Inside the class MagicWizard add or remove pages.

Download PyQT5 Examples