PyQt

Python is not limited to making terminal applications. To create a graphical user interface (GUI) with Python, the module Pyqt can be used. An example Python GUI (Pyqt) application:

pyqt-messagebox
PyQt messagebox

Popular apps made with Pyqt are: Konqueror, the KDE Desktop environment and many others.

Applications made with Python and Pyqt work on Windows, Mac and Unix. There are two major versions of Pyqt: PyQt4 and PyQt5. We recommend going with the later version as the other is older.

To install Pyqt type pip3 install pyqt5 or pip install pyqt5.

Related Courses:

Pyqt Articles
These articles form a short introduction to the PyQt5 module.

 

pyqt5 hello world

PyQt can be used to create a graphical user interface, GUI. Qt was created by Riverbank Computing.
Graphical interfaces made with PyQt can run on all major desktop systems including Microsoft Windows, Apple Mac and Unix.

We will create a Hello World app with PyQt.

pyqt hello world
Python GUI using PyQt: hello world

Related course

Install PyQt

PyQt is available for both Python 2 (2.7.9 tested) and Python 3.

To install write:
pip3 install pyqt5

With apt-get you can use:
python3-pyqt5

PyQt hello world

The app we write will show the message “Hello World” in a graphical window. Import the PyQt5 module.

import sys
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtWidgets import QMainWindow, QLabel, QGridLayout, QWidget
from PyQt5.QtCore import QSize    
     
class HelloWindow(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
 
        self.setMinimumSize(QSize(640, 480))    
        self.setWindowTitle("Hello world") 
        
        centralWidget = QWidget(self)          
        self.setCentralWidget(centralWidget)   
 
        gridLayout = QGridLayout(self)     
        centralWidget.setLayout(gridLayout)  
 
        title = QLabel("Hello World from PyQt", self) 
        title.setAlignment(QtCore.Qt.AlignCenter) 
        gridLayout.addWidget(title, 0, 0)
 
 
if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    mainWin = HelloWindow()
    mainWin.show()
    sys.exit( app.exec_() )

The program starts in the main part. We initialize Qt and create an object of the type HelloWindow. We call the show() method to display the window.

if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    mainWin = HelloWindow()
    mainWin.show()
    sys.exit( app.exec_() )

The HelloWindow class inherits from the class QMainWindow. We call its super method to initialize the window. Several class variables are set: size and window title. We add widgets to the window, including a label widget (QLabel) which displays the message “Hello World”.
 

pyqt5 center window

To center a PyQt window, we need to do a bit of trickery: we need to get the window properties, center point and move it ourself. At the start of the program, it will be in the center of the screen.

Related course

pyqt center screen

We add QDesktopWidget to the list of imports, having:

from PyQt5.QtWidgets import QMainWindow, QLabel, QGridLayout, QWidget, QDesktopWidget

Include this in the window creation method:

qtRectangle = self.frameGeometry()
centerPoint = QDesktopWidget().availableGeometry().center()
qtRectangle.moveCenter(centerPoint)
self.move(qtRectangle.topLeft())

The geometry of the window is then retrieved using:

qtRectangle = self.frameGeometry()

We can output qtRectangle using print(qtRectangle),
this would return PyQt5.QtCore.QRect(0, 0, 640, 480)

Get the center of the screen using

centerPoint = QDesktopWidget().availableGeometry().center()

Set it to the center

qtRectangle.moveCenter(centerPoint)
self.move(qtRectangle.topLeft())

 

pyqt5 button

In this tutorial you’ll learn how to add button widgets to an existing Pyqt window and how to connect a click to a Python method. The button widget is called QPushButton.

If you do not have PyQt installed, see the previous tutorial.

Related course

pyqt5 button example

Start by importing QPushButton

from PyQt5.QtWidgets import QPushButton

In the window constructor, add these lines

pybutton = QPushButton('Click me', self)
pybutton.resize(100,32)
pybutton.move(50, 50)        
pybutton.clicked.connect(self.clickMethod)

The first line creates an object of the type QPushButton.

We resize it to 100 pixels in width and 32 in height. Then we set it to position (50,50) on the window.
The click must be linked to a Python method, clickMethod().

The end program will look like this:

pyqt button
Pyqt button widgets, QPushButton

Complete code resulting in:

import sys
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtWidgets import QMainWindow, QLabel, QGridLayout, QWidget
from PyQt5.QtWidgets import QPushButton
from PyQt5.QtCore import QSize    
     
class MainWindow(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
 
        self.setMinimumSize(QSize(300, 200))    
        self.setWindowTitle("PyQt button example - pythonprogramminglanguage.com") 
        
        pybutton = QPushButton('Click me', self)
        pybutton.clicked.connect(self.clickMethod)
        pybutton.resize(100,32)
        pybutton.move(50, 50)        
    
    def clickMethod(self):
        print('Clicked Pyqt button.')

    
if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    mainWin = MainWindow()
    mainWin.show()
    sys.exit( app.exec_() )

 

pyqt5 message box

When creating a Python GUI, you may want to show a message box at some point.
Pyqt comes with messagebox support in both PyQt4 and PyQt5. The class to be used is QMessageBox.

In this tutorial you’ll learn how to show a message box on buton click.

pyqt-messagebox
PyQt messagebox

Related course:
Python Programming Full Course (Basics, OOP, Modules, PyQt)

QMessageBox example

Import QMessageBox from the PyQt5 widgets

from PyQt5.QtWidgets import QMessageBox

A messagebox can easily be added to the window using the code:

QMessageBox.about(self, "Title", "Message")

Complete code:

import sys
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtWidgets import QMainWindow, QLabel, QGridLayout, QWidget
from PyQt5.QtWidgets import QPushButton
from PyQt5.QtWidgets import QMessageBox
from PyQt5.QtCore import QSize    
     
class MainWindow(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
 
        self.setMinimumSize(QSize(300, 200))    
        self.setWindowTitle("PyQt messagebox example - pythonprogramminglanguage.com") 
        
        pybutton = QPushButton('Show messagebox', self)
        pybutton.clicked.connect(self.clickMethod)
        pybutton.resize(200,64)
        pybutton.move(50, 50)        
    
    def clickMethod(self):
        QMessageBox.about(self, "Title", "Message")

    
if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    mainWin = MainWindow()
    mainWin.show()
    sys.exit( app.exec_() )

 

pyqt5 tooltip

Pyqt supports tool tips, they can be configured for widgets.
A tooltip is a hint in a graphical interface. Tooltips frequently appear when hovering the mouse over a widget (without clicking). Tooltips are not shown on mobile devices because there’s no mouse cursor.

pyqt-tooltip
PyQt tooltip example

Related course
Python Desktop Application Development with PyQt

Pyqt5 tooltip

A tooltip can be set using a widgets setTooltip method.

pybutton.setToolTip('This is a tooltip for the QPushButton widget')  

The setToolTip() method sets the tooltip message for a QtWidget.

Copy/paste example:

import sys
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtWidgets import QMainWindow, QWidget, QPushButton
from PyQt5.QtCore import QSize    
     
class MainWindow(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
 
        self.setMinimumSize(QSize(300, 100))    
        self.setWindowTitle("PyQt tooltip example - pythonprogramminglanguage.com") 
        
        pybutton = QPushButton('Pyqt', self)
        pybutton.clicked.connect(self.clickMethod)
        pybutton.resize(100,32)
        pybutton.move(50, 20)        
        pybutton.setToolTip('This is a tooltip message.')  
        
    def clickMethod(self):
        print('PyQt')

    
if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    mainWin = MainWindow()
    mainWin.show()
    sys.exit( app.exec_() )

 

pyqt menu

Pyqt has menu support. Almost every GUI app has a main menu at the top of the window. Adding a menu works slightly different than adding widgets.

A menu can contain sub menus, they are usually something like (File, Edit, View, History, Help). Every menu has actions. In this tutorial we’ll make a main menu that includes a file menu and actions.
 

pyqt-menu
Pyqt menu

Related course: Python Desktop Application Development with PyQt
 

Pyqt menu example

The menu is created with:

menuBar = self.menuBar()
fileMenu = menuBar.addMenu('&File')

Then actions are added to the file menu:

fileMenu.addAction(newAction)
fileMenu.addAction(openAction)
fileMenu.addAction(exitAction)

These actions must be defined beforehand:

# Create new action
newAction = QAction(QIcon('new.png'), '&New', self)        
newAction.setShortcut('Ctrl+N')
newAction.setStatusTip('New document')
newAction.triggered.connect(self.newCall)

# Create new action
openAction = QAction(QIcon('open.png'), '&Open', self)        
openAction.setShortcut('Ctrl+O')
openAction.setStatusTip('Open document')
openAction.triggered.connect(self.openCall)

# Create exit action
exitAction = QAction(QIcon('exit.png'), '&Exit', self)        
exitAction.setShortcut('Ctrl+Q')
exitAction.setStatusTip('Exit application')
exitAction.triggered.connect(self.exitCall)

Complete code:

import sys
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtWidgets import QMainWindow, QWidget, QPushButton, QAction
from PyQt5.QtCore import QSize    
from PyQt5.QtGui import QIcon
     
class MainWindow(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
 
        self.setMinimumSize(QSize(300, 100))    
        self.setWindowTitle("PyQt menu example - pythonprogramminglanguage.com") 
        
        # Add button widget
        pybutton = QPushButton('Pyqt', self)
        pybutton.clicked.connect(self.clickMethod)
        pybutton.resize(100,32)
        pybutton.move(130, 30)        
        pybutton.setToolTip('This is a tooltip message.')  

        # Create new action
        newAction = QAction(QIcon('new.png'), '&New', self)        
        newAction.setShortcut('Ctrl+N')
        newAction.setStatusTip('New document')
        newAction.triggered.connect(self.newCall)

        # Create new action
        openAction = QAction(QIcon('open.png'), '&Open', self)        
        openAction.setShortcut('Ctrl+O')
        openAction.setStatusTip('Open document')
        openAction.triggered.connect(self.openCall)

        # Create exit action
        exitAction = QAction(QIcon('exit.png'), '&Exit', self)        
        exitAction.setShortcut('Ctrl+Q')
        exitAction.setStatusTip('Exit application')
        exitAction.triggered.connect(self.exitCall)

        # Create menu bar and add action
        menuBar = self.menuBar()
        fileMenu = menuBar.addMenu('&File')
        fileMenu.addAction(newAction)
        fileMenu.addAction(openAction)
        fileMenu.addAction(exitAction)
        
    def openCall(self):
        print('Open')
        
    def newCall(self):
        print('New')
        
    def exitCall(self):
        print('Exit app')
        
    def clickMethod(self):
        print('PyQt')

    
if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    mainWin = MainWindow()
    mainWin.show()
    sys.exit( app.exec_() )

 

PyQt line edit

A textbox or LineEdit can be created using the QLineEdit class. Many applications have text inputs like form fields and the like.

In this tutorial we’ll make an app that displays the name typed in the textbox.

pyqt line edit
Textbox with PyQt

Related course: Python Desktop Application Development with PyQt

QLineEdit Example

We start with the code followed by the explanation.

import sys
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtWidgets import QMainWindow, QWidget, QLabel, QLineEdit
from PyQt5.QtWidgets import QPushButton
from PyQt5.QtCore import QSize    
     
class MainWindow(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
 
        self.setMinimumSize(QSize(320, 140))    
        self.setWindowTitle("PyQt Line Edit example (textfield) - pythonprogramminglanguage.com") 


        self.nameLabel = QLabel(self)
        self.nameLabel.setText('Name:')
        self.line = QLineEdit(self)
        
        self.line.move(80, 20)
        self.line.resize(200, 32)
        self.nameLabel.move(20, 20)
        
        pybutton = QPushButton('OK', self)
        pybutton.clicked.connect(self.clickMethod)
        pybutton.resize(200,32)
        pybutton.move(80, 60)        
        
    def clickMethod(self):
        print('Your name: ' + self.line.text())

    
if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    mainWin = MainWindow()
    mainWin.show()
    sys.exit( app.exec_() )

Start by importing the QLineEdit widget:

from PyQt5.QtWidgets import QLineEdit

We will also add a text label, to show the user what to type.
Import QLabel:

from PyQt5.QtWidgets import QLabel

Then add both to the screen:

self.nameLabel = QLabel(self)
self.nameLabel.setText('Name:')
self.line = QLineEdit(self)
        
self.line.move(80, 20)
self.line.resize(200, 32)
self.nameLabel.move(20, 20)

The text value can be printed using:

print('Your name: ' + self.line.text())