Skip to content

Python PyQt

PyQt is a powerful Python library for creating graphical user interfaces (GUIs), which can be used as an alternative to Python’s built-in Tkinter.

PyQt is the Python binding for the Qt framework and is widely used in desktop application development.

Qt is a cross-platform C++ application development framework.

PyQt allows Python developers to leverage the Qt library to create powerful GUI applications.

PyQt has the following major versions:

  • PyQt4: Binding based on Qt4
  • PyQt5: Binding based on Qt5
  • PyQt6: Binding based on Qt6 (latest version)

Install PyQt5 using pip:

# Install PyQt5
pip install PyQt5

# Install Qt Designer and other tools (optional)
pip install PyQt5-tools

Below is the most basic PyQt program, creating a blank window:

from PyQt5.QtWidgets import QApplication, QWidget

# Create an application instance
app = QApplication([])

# Create the main window
window = QWidget()
window.setWindowTitle("My First PyQt Program")
window.setGeometry(100, 100, 400, 300)  # (x, y, width, height)

# Show the window
window.show()

# Run the application
app.exec_()

  1. QApplication: Manages the control flow and main settings of the GUI application.
  2. QWidget: The most basic window class; all UI components inherit from it.
  3. setWindowTitle(): Sets the window title.
  4. setGeometry(): Sets the window position and size.
  5. show(): Displays the window.
  6. app.exec_(): Starts the event loop, waiting for user interaction.

A typical PyQt application consists of the following parts:

  1. QApplication Object: Every PyQt application needs a QApplication instance
  2. Windows and Widgets: User interface components
  3. Event Loop: The loop that handles user input and system events
  4. Event Handlers: Functions or methods that respond to events
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        
        # Set window title and size
        self.setWindowTitle("My First PyQt Application")
        self.setGeometry(100, 100, 400, 300)  # x, y, width, height
        
        # Create a button
        self.button = QPushButton("Click Me", self)
        self.button.setGeometry(150, 150, 100, 30)
        self.button.clicked.connect(self.button_clicked)
        
    def button_clicked(self):
        print("Button was clicked!")

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


from PyQt5.QtWidgets import QPushButton

button = QPushButton("Click Me", window)
button.move(150, 150)  # Set button position
from PyQt5.QtWidgets import QLabel

label = QLabel("Hello PyQt!", window)
label.move(100, 100)
from PyQt5.QtWidgets import QLineEdit

textbox = QLineEdit(window)
textbox.move(100, 50)

For more common widget content, refer to: https://www.runoob.com/python3/python-pyqt-widgets.html


Using layout managers allows automatic adjustment of widget positions:

from PyQt5.QtWidgets import QVBoxLayout, QLabel, QPushButton

layout = QVBoxLayout()
layout.addWidget(QLabel("Username"))
layout.addWidget(QLineEdit())
layout.addWidget(QPushButton("Login"))
window.setLayout(layout)

For more layout management content, refer to: https://www.runoob.com/python3/python-pyqt-layout.html


PyQt uses the Signal and Slot mechanism to handle events.

PyQt’s signal and slot mechanism is the core mechanism for communication between objects.

  • Signal: A notification emitted when a specific event occurs
  • Slot: A function or method that responds to a signal
from PyQt5.QtWidgets import QPushButton

def on_button_click():
    print("Button was clicked!")

button = QPushButton("Click Me", window)
button.clicked.connect(on_button_click)  # Connect signal and slot
from PyQt5.QtCore import pyqtSignal, QObject

class MyEmitter(QObject):
    my_signal = pyqtSignal(str)  # Define a signal

emitter = MyEmitter()
emitter.my_signal.connect(lambda x: print(f"Signal received: {x}"))
emitter.my_signal.emit("Hello")  # Emit the signal

For more signals and slots content, refer to: https://www.runoob.com/python3/python-pyqt-signals-and-slots.html


Qt Designer is a visual design tool that allows you to drag and drop widgets to design interfaces:

  • Launch Designer (usually located in the Python installation directory under Lib\site-packages\qt5_applications\Qt\bin)

  • Design the interface and save it as a .ui file

  • Convert the .ui file to Python code:

    pyuic5 input.ui -o output.py

Using the generated interface in code:

from PyQt5 import uic

# Load the UI file
Form, Window = uic.loadUiType("output.ui")

# Use the UI
app = QApplication(sys.argv)
window = Window()
form = Form()
form.setupUi(window)
window.show()
sys.exit(app.exec_())

import sys
from PyQt5.QtWidgets import (QApplication, QMainWindow, QTextEdit, 
                            QAction, QFileDialog, QMessageBox)

class Notepad(QMainWindow):
    def __init__(self):
        super().__init__()
        self.initUI()
        
    def initUI(self):
        self.text_edit = QTextEdit(self)
        self.setCentralWidget(self.text_edit)
        
        self.create_actions()
        self.create_menus()
        
        self.setWindowTitle('Simple Notepad')
        self.setGeometry(100, 100, 800, 600)
        
    def create_actions(self):
        # File menu actions
        self.new_action = QAction('New', self)
        self.new_action.setShortcut('Ctrl+N')
        self.new_action.triggered.connect(self.new_file)
        
        self.open_action = QAction('Open', self)
        self.open_action.setShortcut('Ctrl+O')
        self.open_action.triggered.connect(self.open_file)
        
        self.save_action = QAction('Save', self)
        self.save_action.setShortcut('Ctrl+S')
        self.save_action.triggered.connect(self.save_file)
        
        self.exit_action = QAction('Exit', self)
        self.exit_action.setShortcut('Ctrl+Q')
        self.exit_action.triggered.connect(self.close)
        
        # Edit menu actions
        self.copy_action = QAction('Copy', self)
        self.copy_action.setShortcut('Ctrl+C')
        self.copy_action.triggered.connect(self.text_edit.copy)
        
        self.paste_action = QAction('Paste', self)
        self.paste_action.setShortcut('Ctrl+V')
        self.paste_action.triggered.connect(self.text_edit.paste)
        
        self.cut_action = QAction('Cut', self)
        self.cut_action.setShortcut('Ctrl+X')
        self.cut_action.triggered.connect(self.text_edit.cut)
        
    def create_menus(self):
        menubar = self.menuBar()
        
        # File menu
        file_menu = menubar.addMenu('File')
        file_menu.addAction(self.new_action)
        file_menu.addAction(self.open_action)
        file_menu.addAction(self.save_action)
        file_menu.addSeparator()
        file_menu.addAction(self.exit_action)
        
        # Edit menu
        edit_menu = menubar.addMenu('Edit')
        edit_menu.addAction(self.copy_action)
        edit_menu.addAction(self.paste_action)
        edit_menu.addAction(self.cut_action)
        
    def new_file(self):
        self.text_edit.clear()
        
    def open_file(self):
        filename, _ = QFileDialog.getOpenFileName(self, 'Open File')
        if filename:
            try:
                with open(filename, 'r') as f:
                    self.text_edit.setText(f.read())
            except Exception as e:
                QMessageBox.warning(self, 'Error', f'Cannot open file: {e}')
                
    def save_file(self):
        filename, _ = QFileDialog.getSaveFileName(self, 'Save File')
        if filename:
            try:
                with open(filename, 'w') as f:
                    f.write(self.text_edit.toPlainText())
            except Exception as e:
                QMessageBox.warning(self, 'Error', f'Cannot save file: {e}')

if __name__ == '__main__':
    app = QApplication(sys.argv)
    notepad = Notepad()
    notepad.show()
    sys.exit(app.exec_())


Most widgets are located in PyQt5.QtWidgets.

Advanced features (such as multimedia, networking) may require other modules (such as QtCore, QtGui, QtNetwork, etc.).

QListView/QTableView/QTreeView need to be used with data models (such as QStandardItemModel) for greater flexibility.

Other installable extensions:

pip install PyQtWebEngine  # Web support
pip install PyQtChart      # Chart support
Widget Category Widget Name Module Description
Basic Window Widgets QWidget QtWidgets Base class for all user interface objects, can be used as a blank window or container
QMainWindow QtWidgets Main window framework, includes menu bar, toolbar, status bar, etc.
QDialog QtWidgets Dialog base class, used for pop-up windows
Layout Management QVBoxLayout QtWidgets Vertical layout manager
QHBoxLayout QtWidgets Horizontal layout manager
QGridLayout QtWidgets Grid layout manager
QFormLayout QtWidgets Form layout manager (label + input field pairs)
Button Widgets QPushButton QtWidgets Regular button
QRadioButton QtWidgets Radio button
QCheckBox QtWidgets Checkbox
QToolButton QtWidgets Toolbar button (can have icons)
Input Widgets QLineEdit QtWidgets Single-line text input box
QTextEdit QtWidgets Multi-line rich text editor (supports HTML)
QPlainTextEdit QtWidgets Multi-line plain text editor
QSpinBox QtWidgets Integer spin box
QDoubleSpinBox QtWidgets Floating-point spin box
QComboBox QtWidgets Dropdown selection box
QDateEdit QtWidgets Date picker
QTimeEdit QtWidgets Time picker
QDateTimeEdit QtWidgets Date and time picker
QSlider QtWidgets Slider (horizontal/vertical)
QDial QtWidgets Dial knob widget
Display Widgets QLabel QtWidgets Text/image label
QLCDNumber QtWidgets LCD number display
QProgressBar QtWidgets Progress bar
QStatusBar QtWidgets Status bar (usually used with QMainWindow)
Container Widgets QGroupBox QtWidgets Group box (container with a title)
QTabWidget QtWidgets Tab container
QStackedWidget QtWidgets Stacked container (shows one child widget at a time)
QScrollArea QtWidgets Scroll area container
QMdiArea QtWidgets MDI (Multiple Document Interface) area
List/Table/Tree QListWidget QtWidgets List widget (with item management)
QTreeWidget QtWidgets Tree widget
QTableWidget QtWidgets Table widget
QListView QtWidgets List view (requires data model)
QTableView QtWidgets Table view (requires data model)
QTreeView QtWidgets Tree view (requires data model)
Menu/Toolbar QMenuBar QtWidgets Menu bar
QMenu QtWidgets Menu (can contain submenus and actions)
QToolBar QtWidgets Toolbar
QAction QtWidgets Action (used for menu items, toolbar buttons, etc.)
Dialogs QFileDialog QtWidgets File selection dialog
QColorDialog QtWidgets Color selection dialog
QFontDialog QtWidgets Font selection dialog
QInputDialog QtWidgets Input dialog (text, numbers, etc.)
QMessageBox QtWidgets Message box (warning, error, question, etc.)
Graphics View QGraphicsView QtWidgets Graphics view framework (for 2D graphics)
QGraphicsScene QtWidgets Graphics scene (used with QGraphicsView)
Other Feature Widgets QCalendarWidget QtWidgets Calendar widget
QSplashScreen QtWidgets Splash screen
QSystemTrayIcon QtWidgets System tray icon
QWebEngineView QtWebEngineWidgets Web browser component (requires separate PyQtWebEngine installation)