How to create a graphical interface on PyQt5?

онлайн тренажер по питону
Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

What is PyQt5 and What Is It Used For?

PyQt5 is a set of Python bindings for the Qt library. It's a top choice for building cross-platform graphical user interfaces (GUIs). With PyQt5, developers can craft professional desktop applications featuring modern designs and a rich set of functionalities.

Key Features of PyQt5

PyQt5 empowers developers with a wide array of features:

  • Extensive Collection of Ready-Made Widgets via QtWidgets Module: Access a diverse range of pre-built UI elements for rapid development.
  • Window, Button, Input Field, and List Support: Seamlessly integrate essential components for user interaction.
  • Signal and Slot System for Event-Driven Programming: Implement a robust system for handling user actions and application events.
  • Integration with Graphics Elements Through QGraphicsView: Incorporate advanced graphics and visualizations into your applications.
  • Interface Customization with Styles: Tailor the look and feel of your application to match your brand or design preferences.
  • Cross-Platform Compatibility: Develop applications that run seamlessly on multiple operating systems.

Installing the PyQt5 Library

Use the pip package manager to install PyQt5:

pip install PyQt5

Creating a Basic Application Window

Every PyQt5 application starts by creating a QApplication object. This is the main application object that manages all windows and events. The main window is created based on QWidget.

import sys
from PyQt5.QtWidgets import QApplication, QWidget

app = QApplication(sys.argv)
window = QWidget()
window.setWindowTitle("Simple Window")
window.resize(300, 200)
window.show()
sys.exit(app.exec_())

QApplication is a required component for any PyQt5 GUI application. It handles system events and manages the application lifecycle.

Working with Basic Controls

QLineEdit - Text Input Field

QLineEdit is a single-line text input field. This widget is widely used for getting user input.

from PyQt5.QtWidgets import QLineEdit, QVBoxLayout, QPushButton

window = QWidget()
window.setWindowTitle("QLineEdit Example")

layout = QVBoxLayout()

line_edit = QLineEdit()
line_edit.setPlaceholderText("Enter your name")

button = QPushButton("Submit")

def on_click():
    print(f"Hello, {line_edit.text()}!")

button.clicked.connect(on_click)

layout.addWidget(line_edit)
layout.addWidget(button)
window.setLayout(layout)
window.show()

The input field supports various methods for working with text:

  • setText() - Programmatically sets the text
  • text() - Gets the entered text
  • setPlaceholderText() - Sets placeholder text (hint text)
  • setMaxLength() - Limits the maximum input length

QComboBox - Creating Drop-Down Lists

QComboBox allows the user to select one option from a list of options.

from PyQt5.QtWidgets import QComboBox

combo = QComboBox()
combo.addItems(["Select an option", "Python", "C++", "JavaScript"])

def on_selection_change(value):
    print(f"You selected: {value}")

combo.currentTextChanged.connect(on_selection_change)

layout.addWidget(combo)

QComboBox offers several helpful methods:

  • addItem() - Adds a single item
  • addItems() - Adds a list of items
  • currentText() - Gets the selected text
  • currentIndex() - Gets the index of the selected item
  • clear() - Clears all items

QCheckBox - Working with Checkboxes and Signals

QCheckBox allows the user to select or deselect an option.

from PyQt5.QtWidgets import QCheckBox

checkbox = QCheckBox("Agree to terms")

def on_checkbox_state(state):
    if state:
        print("Checkbox is checked")
    else:
        print("Checkbox is unchecked")

checkbox.stateChanged.connect(on_checkbox_state)
layout.addWidget(checkbox)

A checkbox can be in three states:

  • Unchecked
  • Checked
  • Partially checked (for tri-state checkboxes)

Signal and Slot System

Understanding the Event Mechanism

The signal and slot system is the foundation of event-driven programming in PyQt5. A signal is emitted by a widget when a certain event occurs. A slot is a function that is called in response to a signal.

Common widget signals:

  • clicked - For buttons
  • textChanged - For input fields
  • currentTextChanged - For drop-down lists
  • stateChanged - For checkboxes

Connecting Signals to Functions

Use the connect() method to connect a signal to a function:

button.clicked.connect(your_function)

You can also use lambda functions to pass parameters:

button.clicked.connect(lambda: your_function(parameter))

Working with Graphics via QGraphicsView

QGraphicsView provides a powerful tool for displaying graphical elements in an application. This widget works with QGraphicsScene to create complex graphical interfaces.

from PyQt5.QtWidgets import QGraphicsScene, QGraphicsView, QGraphicsEllipseItem

scene = QGraphicsScene()
ellipse = QGraphicsEllipseItem(0, 0, 100, 100)
scene.addItem(ellipse)

graphics_view = QGraphicsView(scene)
layout.addWidget(graphics_view)

QGraphicsView Features

QGraphicsView supports:

  • Zooming and panning
  • Adding various graphic primitives
  • Handling mouse and keyboard events
  • Animating objects
  • Grouping elements

Full Example Application with Interface

import sys
from PyQt5.QtWidgets import (QApplication, QWidget, QVBoxLayout, QPushButton,
                             QLineEdit, QComboBox, QCheckBox, QGraphicsScene, 
                             QGraphicsView, QGraphicsEllipseItem)

def main():
    app = QApplication(sys.argv)
    window = QWidget()
    window.setWindowTitle("Full PyQt5 Interface")

    layout = QVBoxLayout()

    # QLineEdit
    name_input = QLineEdit()
    name_input.setPlaceholderText("Enter name")
    layout.addWidget(name_input)

    # QComboBox
    combo = QComboBox()
    combo.addItems(["Select language", "Python", "C++", "JavaScript"])
    layout.addWidget(combo)

    # QCheckBox
    checkbox = QCheckBox("Agree to terms")
    layout.addWidget(checkbox)

    # QGraphicsView
    scene = QGraphicsScene()
    ellipse = QGraphicsEllipseItem(0, 0, 100, 100)
    scene.addItem(ellipse)

    graphics_view = QGraphicsView(scene)
    layout.addWidget(graphics_view)

    # Button
    button = QPushButton("Submit")

    def on_click():
        print(f"Name: {name_input.text()}")
        print(f"Language: {combo.currentText()}")
        print(f"Agreement: {'Yes' if checkbox.isChecked() else 'No'}")

    button.clicked.connect(on_click)
    layout.addWidget(button)

    window.setLayout(layout)
    window.show()
    sys.exit(app.exec_())

if __name__ == "__main__":
    main()

Interface Layout Management

Layout Manager Types

PyQt5 provides several types of layout managers:

  • QVBoxLayout - Vertically arranges widgets
  • QHBoxLayout - Horizontally arranges widgets
  • QGridLayout - Arranges widgets in a grid
  • QFormLayout - Layout in the form of a form with labels

Configuring Indents and Intervals

Layout managers allow you to configure:

  • Indents from the edges of the window
  • Distance between widgets
  • Element alignment
  • Stretching widgets

Interface Styling

Applying CSS Styles

PyQt5 supports the use of styles similar to CSS to style widgets:

button.setStyleSheet("background-color: green; color: white; border: 2px solid black;")

Creating Themes

You can create complex themes by applying styles to the entire application:

app.setStyleSheet("""
    QWidget {
        background-color: #2b2b2b;
        color: white;
    }
    QPushButton {
        background-color: #404040;
        border: 1px solid #555555;
        padding: 5px;
    }
""")

Working with Menus and Toolbars

Creating a Main Menu

QMainWindow and QMenuBar are used to create a menu:

from PyQt5.QtWidgets import QMainWindow, QMenuBar, QAction

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.menu = self.menuBar()
        file_menu = self.menu.addMenu("File")
        
        open_action = QAction("Open", self)
        open_action.triggered.connect(self.open_file)
        file_menu.addAction(open_action)
    
    def open_file(self):
        print("Opening file")

Adding a Toolbar

A toolbar is created using QToolBar:

toolbar = self.addToolBar("Main Panel")
toolbar.addAction(open_action)

Error Handling and Debugging

Basic Principles of Error Handling

When developing interfaces, it is important to provide error handling:

  • Check the correctness of user input
  • Validate data before processing
  • Inform the user of errors
  • Log critical errors

Using QMessageBox for Notifications

from PyQt5.QtWidgets import QMessageBox

def show_error(message):
    msg_box = QMessageBox()
    msg_box.setIcon(QMessageBox.Critical)
    msg_box.setWindowTitle("Error")
    msg_box.setText(message)
    msg_box.exec_()

Frequently Asked Questions

What is QtWidgets in PyQt5?

QtWidgets is a module containing all the basic widgets for creating a graphical interface. This includes windows, buttons, input fields, lists, tables, and other controls.

How to Transfer Data Between Widgets

The signal and slot system is used to transfer data between widgets. One widget emits a signal when a certain event occurs, and another widget receives this signal through a connected slot.

How to Add a Menu to a PyQt5 Application

To add a menu, use the QMainWindow class instead of QWidget, and the menu itself is created through QMenuBar. Each menu item is a QAction.

What is QApplication and Why is it Needed?

QApplication is the main application object that manages all windows and events. It is required for any GUI application on PyQt5 and provides interaction with the operating system.

How to Handle a Button Click

Handling a button click is done by connecting the clicked signal to a handler function using the connect method.

Can I Use CSS Styles to Design the Interface?

PyQt5 supports the use of styles similar to CSS using the setStyleSheet() method. This allows you to customize the colors, fonts, borders, and other visual properties of widgets.

Useful Resources for Learning

For in-depth study of PyQt5, it is recommended to familiarize yourself with the official documentation and additional materials:

  • Official PyQt5 Documentation
  • Code examples and tutorials from the developer community
  • Forums and communities for sharing experiences

Conclusion

Creating graphical interfaces in Python with PyQt5 opens up broad possibilities for developing modern and user-friendly applications. The article discussed basic and advanced interface elements, the principles of working with signals and slots, the integration of graphic elements, and practical examples of implementation.

Having mastered the basics of PyQt5, developers get a powerful tool for creating full-fledged desktop applications with a professional interface. The widget system, flexible layout, and customization capabilities make PyQt5 an excellent choice for projects of any complexity.

News