[PyQt5] Build a powerful Python graphical user interface application -- Getting Started Guide

 

Author's homepage: boy who loves to laugh. Blog_CSDN blog - deep learning, activities, python field blogger loves to laugh boy. A boy who is good at deep learning, activities, python, etc., and loves to laugh. Focus on algorithms, python, computer vision, image processing, deep learning, pytorch, neural network, opencv fields. https://blog.csdn.net/Code_and516?type=blog Personal profile: Dagong.

Continue to share: machine learning, deep learning, python-related content, daily BUG solutions, and Windows&Linux practical tips.

If you find an error in the article, please point it out, and I will correct it in time. If you have other needs, you can private message me or send me an email: [email protected] 

 

        PyQt5 is a powerful Python library for creating graphical user interface (GUI) applications. It is a Python binding based on the Qt framework that allows developers to easily create rich and interactive applications using the Python language. 

This article will take you to the introductory stage of PyQt5, a Python GUI application


Table of contents

1. Introduction to PyQt5

2. The development history of PyQt5

1. The origin of PyQt

2. Evolution of PyQt

(1)PyQt3

(2)PyQt4

(3) Riverbank from PyQt4 to PyQt5

(4) Open Source License Changes

(5)PyQt5

(6) Transition to Qt6

(7) The future of PyQt6

3. Why choose PyQt5

1. Cross-platform support:

2. Full functionality:

3. The power of the Python language:

4. Rich documentation and community support:

5. Good performance:

6. Wide range of application fields:

Four, some shortcomings of PyQt5

1. The learning curve is steep:

2. Deployment complexity:

3. Licensing issues:

Five, the basic steps of PyQt5

Six, the use of PyQt5

1. Basic use of PyQt5

(1) Install PyQt5

(2) Create the first window 

(3) Add components

(4) Response to events

2. Advanced features of PyQt5

(1) Layout Manager

(2) dialog box

(3) Custom painting

Seven, PyQt5 summary


1. Introduction to PyQt5

        PyQt5 is a powerful Python library for creating graphical user interface (GUI) applications. It is a Python binding for the Qt framework, providing a rich set of tools and components that enable developers to easily create interactive, visual, and responsive applications.

        Qt is a cross-platform C++ application development framework with a wide range of applications, from desktop software to mobile applications to embedded systems. PyQt5 combines the power of Qt with the concise syntax of Python, providing developers with an elegant and efficient way to build GUI applications.

2. The development history of PyQt5

1. The origin of PyQt

        PyQt is a Python binding library developed by Riverbank Computing for the Qt application framework. Qt is a cross-platform C++ application framework created in 1991 by the Norwegian company Trolltech. It provides a rich set of tools and components for developing desktop, mobile and embedded applications.

        The PyQt project was originally created in 1998 by Phil Thompson, who brought the power of Qt to the Python language. Through PyQt, developers can use Python to write applications that utilize the functions of the Qt library, so as to give full play to the simplicity and ease of use of Python and the powerful functions of Qt.

2. Evolution of PyQt

        Over time, PyQt has grown and gained wide acceptance and use throughout the developer community. The following are major releases and milestones for PyQt:

(1)PyQt3

        PyQt3 is the earliest PyQt version and the first official version, released in 2000. Supports Qt 2.x and 3.x versions. It provides Python developers with access to the Qt library, enabling them to create applications with a graphical user interface.

(2)PyQt4

        PyQt4 is an important version released in 2005, which supports the latest Qt 4.x version. Compared to previous versions, PyQt4 introduces many improvements and new features, including better performance, better Python 2.x and 3.x compatibility, and support for new Qt features.

(3) Riverbank from PyQt4 to PyQt5

        With the development of the Qt framework and the release of the Qt 5 version, Riverbank Computing decided to upgrade PyQt4 to PyQt5. This transition was made to keep pace with Qt 5 and take advantage of the latest improvements in the Qt framework in terms of visualization and interaction.

(4) Open Source License Changes

        Unlike PyQt3 and PyQt4 which adopt the GPL license, PyQt5 switched to a commercial license in 2010. This means that developers can use PyQt5 to create closed-source commercial applications, but need to purchase the corresponding license.

(5)PyQt5

        PyQt5 is the latest and currently most widely used version of PyQt, which was released in 2013. It fully supports Qt 5.x and provides many improvements and new features. In addition to supporting Python 2.x, PyQt5 also adds strong support for Python 3.x, enabling developers to use the latest Python version to develop applications.

(6) Transition to Qt6

        With the release of the Qt 6 framework, PyQt5 also started transitioning to Qt 6 in late 2020. This enables developers to take advantage of new Qt 6 features and migrate existing PyQt5 applications to the new framework.

(7) The future of PyQt6

        Currently, PyQt6 is under development and is expected to be released in the next few years. PyQt6 will continue to provide support for the latest version of Qt with more enhancements and performance optimizations.

3. Why choose PyQt5

        In today's fast-moving world of software development, choosing a suitable GUI (Graphical User Interface) toolkit is crucial. As a powerful and widely used framework, PyQt5 is favored by more and more developers. Here are a few important reasons to choose PyQt5:

1. Cross-platform support :

        PyQt5 can run on multiple operating systems, including Windows, macOS, and Linux. This enables developers to easily write code once and run it stably on various platforms.

2. Full functionality :

        PyQt5 provides a wealth of functions and components, covering a variety of solutions, from basic window layout to complex data visualization and 3D graphics. Whether you are developing desktop applications, mobile applications or web applications, PyQt5 provides flexible and easy-to-use tools.

3. The power of the Python language:

        As an extension library of the Python language, PyQt5 takes full advantage of the simplicity and readability of Python. Python is a widely used high-level programming language with a clear syntax that is easy to learn and understand. Using PyQt5, developers can build applications faster and improve development efficiency.

4. Rich documentation and community support :

        PyQt5 has extensive documentation and an active developer community, which means you can easily find solutions to your problems and sample code. Not only that, PyQt5 also provides detailed official documents and tutorials to help you get started quickly and master more advanced concepts and techniques.

5. Good performance :

        Since PyQt5 is built based on the underlying Qt framework, it has excellent performance. The Qt framework has been developed and optimized over the years, and it excels when dealing with large amounts of data and complex operations. Whether you are developing small applications or large enterprise-level software, PyQt5 can meet your performance needs.

6.  Wide application fields :

        PyQt5 has been widely used in various fields, including scientific computing, data visualization, game development, Internet of Things, etc. This means that using PyQt5, you will be able to face various projects and have the opportunity to participate in innovative work in different fields.

Four, some shortcomings of PyQt5

        PyQt5 provides a rich and powerful set of tools and features that enable developers to create a wide variety of cross-platform applications. However, like any technology, PyQt5 has some advantages and disadvantages.

        The advantages have already been mentioned when choosing PyQt5 , now let's talk about its disadvantages:

1.  The learning curve is steep :

        For beginners, the learning curve of PyQt5 can be relatively steep. It requires mastery of the Python programming language as well as PyQt5's own APIs and concepts. Therefore, for those developers who do not have any GUI development experience, learning PyQt5 may take some time and effort.

2.  Deployment complexity :

        Since PyQt5 is a large library, there may be some complexities involved when deploying applications. Especially when deploying across platforms, additional setup and configuration may be required to ensure that the application functions properly on different operating systems.

3.  Licensing issues :

        The license of PyQt5 is divided into commercial version and open source version. The commercial version requires the purchase of a license to use, while the open source version is available under certain conditions. This means that if a developer wants to use PyQt5 in a commercial project, additional costs may be required.

Five, the basic steps of PyQt5

        To get started with PyQt5, here are some basic steps:

  1. Install the PyQt5 library: Use the pip command to install the PyQt5 library on the command line.

  2. Import required modules: According to the needs of the application, import the required PyQt5 modules, such as QApplication, QWidgetetc.

  3. Create an application object: instantiate an QApplicationobject as the entry point for the entire application.

  4. Create windows and components: Create a main window ( QWidget), and add the required UI components, such as labels, buttons, etc.

  5. Set window properties and layout: set the title, size, position and other properties of the window, and use the layout manager to automatically manage the position and size of components.

  6. Connecting signals and slots: By calling component methods (such as clicked.connect(), textChanged.connect()etc.), connect signals and slot functions to implement event processing and interaction logic.

  7. Display the window and run the application: By calling show()the method of the window, the window is displayed, and app.exec_()the event loop of the application is started by calling.

Six, the use of PyQt5

1. Basic use of PyQt5

(1) Install PyQt5

        To start using PyQt5, you first need to install it. PyQt5 can be installed from the command line using the pip command:

pip install pyqt5

(2) Create the first window 

        Here is a simple sample code showing how to create a basic PyQt5 window:

import sys
from PyQt5.QtWidgets import QApplication, QWidget

if __name__ == '__main__':
    app = QApplication(sys.argv)
    
    # 创建窗口
    window = QWidget()
    window.setWindowTitle('My First PyQt5 Window')
    window.setGeometry(100, 100, 300, 200)
    window.show()
    
    sys.exit(app.exec_())

        In this example, I first imported QApplicationthe and QWidgetclass. Then, in if __name__ == '__main__':the statement block, I create an QApplicationobject and set the title, position and size of the window. Finally, the window is displayed by calling show()the method, and app.exec_()the application's event loop is started by calling the method. 

(3) Add components

        PyQt5 provides many built-in UI components, such as buttons, text input boxes and labels. Complex user interfaces can be built by creating these components and adding them to windows.

import sys
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QPushButton

if __name__ == '__main__':
    app = QApplication(sys.argv)
    
    # 创建窗口
    window = QWidget()
    window.setWindowTitle('My First PyQt5 Window')
    window.setGeometry(100, 100, 300, 200)
    
    # 添加标签
    label = QLabel('Hello World!', window)
    label.move(100, 50)
    
    # 添加按钮
    button = QPushButton('Click Me!', window)
    button.move(100, 100)
    
    window.show()
    
    sys.exit(app.exec_())

        In this example, I create a QLabeland a QPushButtoncomponent and add them to the window. By calling move()the method, we can set the position of the component in the window. 

(4) Response to events

        PyQt5 allows developers to handle events by connecting signals and slots. A signal is a specific action emitted by a component, while a slot is a specific function associated with it. 

import sys
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QPushButton
from PyQt5.QtCore import Qt

def button_clicked():
    label.setText('Button Clicked!')

if __name__ == '__main__':
    app = QApplication(sys.argv)
    
    # 创建窗口
    window = QWidget()
    window.setWindowTitle('My First PyQt5 Window')
    window.setGeometry(100, 100, 300, 200)
    
    # 添加标签
    label = QLabel('Hello World!', window)
    label.move(100, 50)
    
    # 添加按钮
    button = QPushButton('Click Me!', window)
    button.move(100, 100)
    button.clicked.connect(button_clicked)
    
    window.show()
    
    sys.exit(app.exec_())

        In this example, I've defined a button_clicked()function called , which is called when the button is clicked. Then, clicked.connect()connect the function to the button's clickedsignal by calling the method. 

2. Advanced features of PyQt5

        In addition to basic windows and components, PyQt5 also provides many advanced features to help developers build complex and interactive GUI applications.

(1) Layout Manager

        The layout manager is a commonly used tool in PyQt5, which is used to automatically manage the position and size of components in the window. PyQt5 provides several different types of layout managers, including horizontal layout, vertical layout, grid layout, etc.

import sys
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QLabel, QPushButton

if __name__ == '__main__':
    app = QApplication(sys.argv)
    
    # 创建窗口
    window = QWidget()
    window.setWindowTitle('PyQt5 Layout Example')
    window.setGeometry(100, 100, 300, 200)
    
    # 创建垂直布局管理器
    layout = QVBoxLayout(window)
    
    # 添加标签
    label = QLabel('Hello World!')
    layout.addWidget(label)
    
    # 添加按钮
    button = QPushButton('Click Me!')
    layout.addWidget(button)
    
    window.show()
    
    sys.exit(app.exec_())

        In this example, I create a vertical layout manager and add labels and buttons to the layout. addWidget()Components can be added to the layout manager  by calling the method.

(2) dialog box

        Dialog boxes are common GUI components used to interact with users, such as entering text, selecting files, and so on. PyQt5 provides various types of dialogs, such as message boxes, input dialogs, file dialogs, etc.

import sys
from PyQt5.QtWidgets import QApplication, QWidget, QMessageBox, QInputDialog, QFileDialog,QLabel,QVBoxLayout,QPushButton

def show_message_box():
    QMessageBox.information(window, 'Message', 'Hello World!')

def show_input_dialog():
    text, ok = QInputDialog.getText(window, 'Input', 'Enter your name:')
    if ok and text:
        label.setText(f'Hello, {text}!')

def show_file_dialog():
    filename, _ = QFileDialog.getOpenFileName(window, 'Open File', '', 'Text files (*.txt)')
    if filename:
        with open(filename, 'r') as file:
            content = file.read()
            label.setText(content)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    
    # 创建窗口
    window = QWidget()
    window.setWindowTitle('PyQt5 Dialog Example')
    window.setGeometry(100, 100, 300, 200)
    
    # 创建布局管理器
    layout = QVBoxLayout(window)
    
    # 添加标签
    label = QLabel('Hello World!')
    layout.addWidget(label)
    
    # 添加按钮
    message_button = QPushButton('Show Message Box')
    message_button.clicked.connect(show_message_box)
    layout.addWidget(message_button)
    
    input_button = QPushButton('Show Input Dialog')
    input_button.clicked.connect(show_input_dialog)
    layout.addWidget(input_button)
    
    file_button = QPushButton('Show File Dialog')
    file_button.clicked.connect(show_file_dialog)
    layout.addWidget(file_button)
    
    window.show()
    
    sys.exit(app.exec_())

        In this example, I defined three functions for displaying a message box, an input dialog, and a file dialog. By connecting the button's clickedsignal, we can call the corresponding function when the button is clicked. 

(3) Custom painting

        PyQt5 also allows developers to customize the painting to create components with unique appearance and interaction effects.

import sys
from PyQt5.QtWidgets import QApplication, QWidget
from PyQt5.QtGui import QPainter, QColor
from PyQt5.QtCore import Qt

class CustomWidget(QWidget):
    def __init__(self):
        super().__init__()
    
    def paintEvent(self, event):
        painter = QPainter(self)
        painter.setBrush(Qt.red)
        painter.drawRect(10, 10, 100, 100)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    
    # 创建窗口
    window = CustomWidget()
    window.setWindowTitle('PyQt5 Custom Widget')
    window.setGeometry(100, 100, 300, 200)
    
    window.show()
    
    sys.exit(app.exec_())

        In this example, I created a CustomWidgetcustom window class called and overridden paintEvent()the method. By using QPainterobjects we can draw rectangles on the window. 

Seven, PyQt5 summary

        Through the introduction of this article, we understand the advantages and characteristics of PyQt5. As a powerful and easy-to-use Python library, PyQt5 takes full advantage of the functions of the Qt framework, enabling developers to easily create interactive and beautiful GUI applications. It is cross-platform, rich in functions, easy to learn and use, and supported by open source and active communities, so it has become the first choice of many developers.

        Using PyQt5, developers can quickly build feature-rich, high-quality applications to meet the needs of various fields. Both beginners and experienced developers can give full play to the advantages of PyQt5 and enjoy the fun of GUI development.

        PyQt5 is an active project and will be continuously improved and developed. It provides developers with powerful and comprehensive GUI development capabilities by supporting the latest Qt version, providing more examples and cases, optimizing performance and stability, integrating more third-party libraries and tools, and supporting mobile application development. Changing application requirements. PyQt5 has great potential to become the tool of choice for developing GUI applications, both on desktop and mobile.

        As a powerful and continuously developing Python library, PyQt5 provides developers with rich GUI development capabilities. Although some challenges may be faced during the development process, with reasonable learning and practice, and active participation in the community, developers can overcome these challenges and maximize the advantages of PyQt5. Continuous learning and staying abreast of technology are also key to meeting the challenge. Through continuous improvement and adaptation to changes, PyQt5 is expected to continue to be one of the preferred tools for developers to build powerful GUI applications.

        PyQt5 provides rich functionality and flexibility, enabling developers to create powerful graphical user interface applications. In addition, PyQt5 provides a wealth of advanced features that enable developers to build complex and interactive GUI applications.

        In summary, PyQt5 is a powerful and flexible library for creating graphical user interface (GUI) applications. This article introduces you to the getting started guide of PyQt5, including installing PyQt5, creating the first window, adding components, and responding to events. It also introduces several commonly used advanced functions such as layout managers, dialog boxes, and custom painting. Hope this article helps you get started with PyQt5 and build impressive and interactive applications. Continue to learn and explore more features of PyQt5, you will discover its unlimited potential!

Guess you like

Origin blog.csdn.net/Code_and516/article/details/131569260