杰瑞科技汇

Qt Designer与Python如何高效结合使用?

Of course! Using Qt Designer with Python is one of the most popular and efficient ways to create graphical user interfaces (GUIs). It allows you to design your application's layout visually and then write the Python logic to connect it to your backend code.

Qt Designer与Python如何高效结合使用?-图1
(图片来源网络,侵删)

Here’s a comprehensive guide covering everything from the basics to best practices.


The Core Concept: The Three-Step Process

The workflow is beautifully simple and separates design from logic:

  1. Design: Use the Qt Designer application to create a .ui file (an XML description of your UI).
  2. Convert: Use a command-line tool (pyuic6) to convert the .ui file into a Python file (.py).
  3. Integrate: Import the generated Python file into your main application script and add your logic (e.g., connecting buttons to functions).

Step 1: Installation

First, you need to install the necessary libraries. The standard is PyQt6 or PySide6. They are nearly identical in syntax, with PySide6 being the official, open-source version from The Qt Company.

# For PyQt6
pip install PyQt6
# For PySide6 (Recommended)
pip install PySide6

PySide6 conveniently comes with the pyside6-uic tool, which is the same as pyuic6.

Qt Designer与Python如何高效结合使用?-图2
(图片来源网络,侵删)

Step 2: Designing the UI with Qt Designer

  1. Launch Qt Designer:

    • From the command line: pyside6-designer (or pyqt6-designer).
    • From the start menu: If you installed via a package manager, it might be available as "Qt Designer".
  2. Create a New Form:

    • When Qt Designer opens, you'll see a "New Form" dialog.
    • Choose "Main Window" for a classic application with menus, a toolbar, and a status bar.
    • Click "Create".
  3. Build Your Interface:

    • The Widget Box on the left contains all the UI components (Buttons, Labels, Line Edits, etc.).
    • Drag and drop components onto your form.
    • Use the Property Editor on the right to change properties (like object names, text, sizes). The most important property is objectName, as you'll use this to refer to the widget in Python.
    • Use the Layout tools (on the top toolbar) to arrange your widgets. This is crucial for creating responsive interfaces that resize correctly.
  4. Save the File:

    Qt Designer与Python如何高效结合使用?-图3
    (图片来源网络,侵删)
    • Go to File > Save As... and save your file as mainwindow.ui. This is the XML representation of your design.

Step 3: Converting the .ui File to a Python Module

Now, you need to turn your mainwindow.ui file into a Python file that you can import.

Open your terminal or command prompt and run the following command:

# For PySide6
pyside6-uic mainwindow.ui -o ui_mainwindow.py
# For PyQt6
pyuic6 mainwindow.ui -o ui_mainwindow.py
  • mainwindow.ui: Your input design file.
  • -o ui_mainwindow.py: The output Python file. It's a common convention to prefix it with ui_.

The generated ui_mainwindow.py file will contain a class named Ui_MainWindow. This class has a setupUi method that, when called, builds the entire UI from your design.


Step 4: Integrating the UI into Your Python Application

This is where you connect your UI to your application's logic. Create a new Python file, for example, app.py.

The key is to create a custom class that inherits from both QMainWindow (the main window type you designed) and Ui_MainWindow (the class generated from your .ui file).

Here is a complete, well-commented example.

app.py

import sys
from PySide6.QtWidgets import QApplication, QMainWindow, QMessageBox
# For PyQt6, use: from PyQt6.QtWidgets import QApplication, QMainWindow, QMessageBox
# Import the UI class from the generated Python file
from ui_mainwindow import Ui_MainWindow
class MainWindow(QMainWindow, Ui_MainWindow):
    def __init__(self):
        # Call the constructors of both parent classes
        super().__init__()
        # This method sets up all the UI elements from the .ui file
        self.setupUi(self)
        # --- Connect signals (from UI) to slots (your Python methods) ---
        self.pushButton.clicked.connect(self.on_button_click)
        self.actionExit.triggered.connect(self.close)
    def on_button_click(self):
        """This method is called when the pushButton is clicked."""
        # Get the text from the lineEdit
        name = self.lineEdit.text()
        # Show a message box
        if name:
            QMessageBox.information(self, "Hello!", f"Hello, {name}!")
        else:
            QMessageBox.warning(self, "Input Error", "Please enter a name.")
if __name__ == "__main__":
    # Create the application instance
    app = QApplication(sys.argv)
    # Create an instance of our MainWindow
    window = MainWindow()
    # Show the window
    window.show()
    # Start the application's event loop
    sys.exit(app.exec())

Explanation of app.py:

  1. from ui_mainwindow import Ui_MainWindow: Imports the class that defines your UI.
  2. class MainWindow(QMainWindow, Ui_MainWindow):: This is the magic. Your new class inherits from both QMainWindow (which provides the window frame, menus, etc.) and Ui_MainWindow (which provides all the widgets you designed).
  3. self.setupUi(self): This is the crucial line from the generated code. It takes the UI definition and builds it inside the self object (our MainWindow instance).
  4. self.pushButton.clicked.connect(self.on_button_click): This is signal and slot.
    • Signal: self.pushButton.clicked is an event that the button emits when it's clicked.
    • Slot: self.on_button_click is the Python method we want to execute when the signal is emitted.
    • The .connect() method links them together.
  5. self.lineEdit.text(): This is how you access a widget's properties. We set the objectName of the line edit to lineEdit in Qt Designer, so we can access it directly in Python.
  6. QMessageBox.information(...): A simple way to show pop-up dialogs to the user.

Advanced: Loading .ui Files at Runtime (Recommended for Development)

Converting the .ui file to a .py file every time you make a design change is tedious. A better approach is to load the .ui file directly at runtime. This way, you can modify the .ui file and immediately run your Python script to see the changes without needing to re-convert.

You'll need the uic module for this.

app_runtime.py

import sys
from PySide6.QtWidgets import QApplication, QMainWindow, QMessageBox
# For PyQt6, use: from PyQt6.QtWidgets import QApplication, QMainWindow, QMessageBox
from PySide6 import uic
# For PyQt6, use: from PyQt6 import uic
class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        # Load the UI file directly
        uic.loadUi("mainwindow.ui", self)
        # --- Connect signals to slots ---
        self.pushButton.clicked.connect(self.on_button_click)
        self.actionExit.triggered.connect(self.close)
    def on_button_click(self):
        """This method is called when the pushButton is clicked."""
        name = self.lineEdit.text()
        if name:
            QMessageBox.information(self, "Hello!", f"Hello, {name}!")
        else:
            QMessageBox.warning(self, "Input Error", "Please enter a name.")
if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec())

Key Difference:

  • uic.loadUi("mainwindow.ui", self) replaces the from ui_mainwindow import ... and self.setupUi(self) lines. It loads the UI from the XML file and applies it to the self object.

This runtime loading approach is highly recommended for development workflows. You only need to use the pyside6-uic command when you are ready to distribute your application and want to avoid shipping the separate .ui file.


Best Practices and Tips

  1. Naming Convention: Always set a meaningful objectName for every widget you plan to interact with in Python (e.g., pushButton, lineEdit, listWidget).
  2. Use Layouts: Always use layouts (QVBoxLayout, QHBoxLayout, etc.) instead of hard-coding widget positions and sizes. This makes your UI responsive.
  3. Separate Logic: Keep your UI definition (.ui file) and your application logic (.py files) as separate as possible. This makes your code much easier to maintain.
  4. Styling: Use Qt Designer's Style Sheet editor (right-click a widget -> "Change Style Sheet...") to apply CSS-like styling to your widgets. It's a powerful way to change colors, fonts, and borders.
  5. Custom Widgets: You can create your own custom widgets in Python and then promote them in Qt Designer. This allows you to design complex, reusable components visually.
分享:
扫描分享到社交APP
上一篇
下一篇