[100 days proficient in python] Day37: GUI interface programming_PyQt from entry to actual combat (on)_PyQt6 basic components, events and signal slots, interface design

Table of contents

 Column Guide 

1 Introduction to PyQt6:

1.1 Install PyQt6 and related tools:

1.2 Basic knowledge of PyQt6:

1.2.1 Basic concepts and components of Qt:

1.2.2 Create and use basic components such as Qt windows, labels, buttons, etc.

1.2.3 Layout Manager: vertical layout, horizontal layout, grid layout, etc.:

2 Event handling and signal slots

2.1 The concept of events and signals

2.2 Handling user input: mouse clicks, keyboard keys, etc.

2.3 Signal slot mechanism: connecting signal and slot functions

3 Qt interface design

3.1 Use Qt Designer to create an interface

3.2 Set interface style and theme:

3.3 Custom Style Sheets


 Column Guide 

Column subscription address: https://blog.csdn.net/qq_35831906/category_12375510.html


1 Introduction to PyQt6:

        PyQt6 is a Python library that provides Python bindings to the Qt 6 C++ library, enabling developers to use Python to create rich GUI applications. Qt 6 is a widely used cross-platform application framework that provides a rich set of tools and components for building desktop, mobile and embedded applications. PyQt6 allows developers to take full advantage of the features of Qt 6 while developing in Python.

1.1 Install PyQt6 and related tools:

To install PyQt6, you can use the following command:

pip install PyQt6

1.2 Basic knowledge of PyQt6:

1.2.1 Basic concepts and components of Qt:

  • QWidget : It is the base class of all Qt widgets, which provides basic window functions.
  • QLabel : used to display text or images.
  • QPushButton : used to create buttons.
  • QLineEdit : Used to receive single-line text input.
  • QTextEdit : used to receive multi-line text input.

1.2.2 Create and use basic components such as Qt windows, labels, buttons, etc.

The following example shows how to create a simple PyQt6 window and add a label and button to the window:

import sys
from PyQt6.QtWidgets import QApplication, QMainWindow, QLabel, QPushButton

class MyWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("PyQt6 Example")
        self.setGeometry(100, 100, 400, 300)

        label = QLabel("Hello, PyQt6!", self)
        label.move(150, 150)

        button = QPushButton("Click Me", self)
        button.setGeometry(150, 200, 100, 30)
        button.clicked.connect(self.on_button_click)

    def on_button_click(self):
        print("Button Clicked!")

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

1.2.3 Layout Manager: vertical layout, horizontal layout, grid layout, etc.:

Layout managers are used to organize and arrange components on the interface. Here's an example using vertical and horizontal layouts:

import sys
from PyQt6.QtWidgets import QApplication, QMainWindow, QVBoxLayout, QPushButton, QLabel, QWidget

class MyWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Layout Example")
        self.setGeometry(100, 100, 400, 300)

        main_widget = QWidget(self)
        self.setCentralWidget(main_widget)

        layout = QVBoxLayout()

        label = QLabel("Hello, PyQt6!", self)
        layout.addWidget(label)

        button = QPushButton("Click Me", self)
        layout.addWidget(button)
        
        main_widget.setLayout(layout)

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

2 Event handling and signal slots

2.1 The concept of events and signals

        In PyQt6, events are actions related to user interaction or system operation. Signals are notifications of events emitted by objects, and slots are functions that respond to signals.

2.2 Handling user input: mouse clicks, keyboard keys, etc.

        You can handle different user input events by overriding QWidget's event handling methods. For example, to handle mouse click events:

import sys
from PyQt6.QtWidgets import QApplication, QMainWindow, QLabel
from PyQt6.QtCore import Qt

class MyWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Event Handling Example")
        self.setGeometry(100, 100, 400, 300)

        self.label = QLabel("Click anywhere in the window", self)
        self.label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        self.label.setGeometry(0, 100, 400, 50)

    def mousePressEvent(self, event):
        if event.button() == Qt.MouseButton.LeftButton:
            self.label.setText("Left mouse button clicked")
        elif event.button() == Qt.MouseButton.RightButton:
            self.label.setText("Right mouse button clicked")

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

2.3 Signal slot mechanism: connecting signal and slot functions

Using the signal-slot mechanism, you can establish communication between objects. Here is an example of a button click signal connected to a slot function:

import sys
from PyQt6.QtWidgets import QApplication, QMainWindow, QPushButton, QLabel, QLineEdit, QCheckBox

class MyWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Signal Slot Example")
        self.setGeometry(100, 100, 400, 300)

        # 创建一个标签,用于显示按钮点击次数
        self.label = QLabel("Click the button", self)
        self.label.setGeometry(150, 30, 150, 30)

        # 创建一个按钮,并连接点击事件到槽函数
        button = QPushButton("Click Me", self)
        button.setGeometry(150, 70, 100, 30)
        button.clicked.connect(self.on_button_click)

        self.counter = 0  # 记录按钮点击次数的计数器

        # 创建一个复选框,用于启用/禁用输入框
        self.checkbox = QCheckBox("Enable Input", self)
        self.checkbox.setGeometry(100, 120, 200, 30)
        self.checkbox.toggled.connect(self.on_checkbox_toggled)

        # 创建一个文本标签和输入框
        self.input_label = QLabel("Enter text:", self)
        self.input_label.setGeometry(80, 160, 100, 30)

        self.input_text = QLineEdit(self)
        self.input_text.setGeometry(180, 160, 150, 30)
        self.input_text.setEnabled(False)  # 初始状态下禁用输入框
        self.input_text.textChanged.connect(self.on_text_changed)

    def on_button_click(self):
        self.counter += 1
        self.label.setText(f"Button Clicked {self.counter} times!")

    def on_checkbox_toggled(self, checked):
        # 当复选框状态改变时,启用/禁用输入框
        self.input_text.setEnabled(checked)
        if not checked:
            self.input_text.clear()

    def on_text_changed(self, text):
        # 当输入框文本改变时,更新标签显示的文本
        self.label.setText(f"Input Text: {text}")

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

3 Qt interface design

3.1 Use Qt Designer to create an interface

        Qt Designer is a visual interface design tool, which can help you create interfaces intuitively, and then combine the designed interface with PyQt code. Here are a simple steps to use Qt Designer:

Use Qt Designer to create the interface:

  1. Open the Qt Designer tool.
  2. Design interface: drag and drop components, set properties, layout, etc.
  3. Save the design as .uia file.
  4. Use pyuicthe tool to .uiconvert the file to Python code.

If your .uifile is named my_ui.ui, you can convert it to Python code with:

pyuic6 my_ui.ui -o my_ui.py

3.2 Set interface style and theme:

        You can use Qt's style sheets to customize the look and feel of the interface. Style sheets use a CSS-like syntax. Here is a simple example:

from PyQt6.QtWidgets import QApplication, QMainWindow, QPushButton

app = QApplication([])

# 创建窗口和按钮
window = QMainWindow()
button = QPushButton("Styled Button")
window.setCentralWidget(button)

# 设置样式表
style = """
    QPushButton {
        background-color: #4CAF50;
        color: white;
        padding: 10px 20px;
        border: none;
    }
"""
button.setStyleSheet(style)

window.show()
app.exec()

 Example 2:

import sys
from PyQt6.QtWidgets import QApplication, QMainWindow, QPushButton, QVBoxLayout, QLabel, QWidget
from PyQt6.QtGui import QPalette, QColor
from PyQt6.QtCore import Qt


class MyWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        # 设置窗口标题和尺寸
        self.setWindowTitle("Styled Button Example")
        self.setGeometry(100, 100, 400, 300)

        # 创建中央部件
        self.central_widget = QWidget(self)
        self.setCentralWidget(self.central_widget)

        # 设置背景颜色
        palette = QPalette()
        palette.setColor(QPalette.ColorRole.Window, QColor(240, 240, 240))
        self.central_widget.setPalette(palette)

        # 创建垂直布局管理器
        layout = QVBoxLayout()
        self.central_widget.setLayout(layout)

        # 创建一个标签,显示按钮点击状态
        self.label = QLabel("Button not clicked", self)
        layout.addWidget(self.label, alignment=Qt.AlignmentFlag.AlignCenter)

        # 设置按钮样式表
        style = """
            QPushButton {
                background-color: #3498db;
                color: white;
                padding: 10px 20px;
                border: none;
                border-radius: 5px;
            }

            QPushButton:hover {
                background-color: #2980b9;
            }
        """
        self.button = QPushButton("Styled Button", self)
        self.button.setStyleSheet(style)
        layout.addWidget(self.button, alignment=Qt.AlignmentFlag.AlignCenter)
        self.button.clicked.connect(self.on_button_click)

        # 创建切换主题按钮
        self.theme_button = QPushButton("Change Theme", self)
        layout.addWidget(self.theme_button, alignment=Qt.AlignmentFlag.AlignCenter)
        self.theme_button.clicked.connect(self.change_theme)

    def on_button_click(self):
        # 当按钮被点击时,更新标签文本
        self.label.setText("Button clicked!")

    def change_theme(self):
        # 切换主题样式表
        new_style = """
            QPushButton {
                background-color: #e74c3c;
                color: white;
                padding: 10px 20px;
                border: none;
                border-radius: 5px;
            }

            QPushButton:hover {
                background-color: #c0392b;
            }
        """
        self.button.setStyleSheet(new_style)


if __name__ == "__main__":
    # 创建应用程序实例并显示窗口
    app = QApplication(sys.argv)
    window = MyWindow()
    window.show()
    sys.exit(app.exec())

 3.3 Custom Style Sheets

        Custom style sheets are a way to modify the appearance of interface components in Qt applications using the CSS (Cascading Style Sheets) syntax. By customizing the style sheet, you can change the background, color, font, border, etc. of the component, so as to realize the personalization and beautification of the interface. The following explains in detail how to use custom style sheets, and provides an example:

Use a custom stylesheet:

  1. Basic syntax: Custom style sheets use CSS syntax to describe the appearance of components. By setting properties and values, you can define the appearance of various components such as buttons, labels, and text boxes.

  2. Selector: A selector is used to specify the component to apply the style to. For example, use QPushButtona selector to specify styles to apply to button components.

  3. Attributes and values: In the selector, you can set multiple attributes and values, such as background-color, color, paddingetc. Each attribute is :separated by a colon, and each style declaration is ;separated by a semicolon.

  4. Pseudo-state selectors: You can also use pseudo-state selectors such as :hoverto define styles on mouseover.

 Here's an example showing how to beautify a button component with a custom stylesheet:

import sys
from PyQt6.QtWidgets import QApplication, QMainWindow, QPushButton, QVBoxLayout, QLabel, QWidget
from PyQt6.QtGui import QPalette, QColor
from PyQt6.QtCore import Qt

app = QApplication(sys.argv)

class MyWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        # 设置窗口标题和尺寸
        self.setWindowTitle("Styled Interface Example")
        self.setGeometry(100, 100, 400, 300)

        # 创建中央部件
        self.central_widget = QWidget(self)
        self.setCentralWidget(self.central_widget)

        # 创建垂直布局管理器
        layout = QVBoxLayout()
        self.central_widget.setLayout(layout)

        # 创建一个标签,显示欢迎信息
        self.label = QLabel("Welcome to Styled Interface!", self)
        layout.addWidget(self.label, alignment=Qt.AlignmentFlag.AlignCenter)

        # 创建三个样式化的按钮并添加到布局
        self.button1 = QPushButton("Styled Button 1", self)
        layout.addWidget(self.button1)
        self.button1.setStyleSheet("background-color: #3498db; color: white; padding: 10px 20px; border: none; border-radius: 5px;")

        self.button2 = QPushButton("Styled Button 2", self)
        layout.addWidget(self.button2)
        self.button2.setStyleSheet("background-color: #e74c3c; color: white; padding: 10px 20px; border: none; border-radius: 5px;")

        self.button3 = QPushButton("Styled Button 3", self)
        layout.addWidget(self.button3)
        self.button3.setStyleSheet("background-color: #27ae60; color: white; padding: 10px 20px; border: none; border-radius: 5px;")

        # 创建切换主题按钮并连接槽函数
        self.theme_button = QPushButton("Change Theme", self)
        layout.addWidget(self.theme_button)
        self.theme_button.clicked.connect(self.change_theme)

    def change_theme(self):
        # 切换按钮的主题样式表
        new_style = """
            QPushButton {
                background-color: #9b59b6;
                color: white;
                padding: 10px 20px;
                border: none;
                border-radius: 5px;
            }
            
            QPushButton:hover {
                background-color: #8e44ad;
            }
        """
        self.button1.setStyleSheet(new_style)
        self.button2.setStyleSheet(new_style)
        self.button3.setStyleSheet(new_style)

if __name__ == "__main__":
    # 创建应用程序实例并显示窗口
    window = MyWindow()
    window.show()
    sys.exit(app.exec())

Guess you like

Origin blog.csdn.net/qq_35831906/article/details/132317189