杰瑞科技汇

python qt designer

Of course! Let's dive deep into using Python with Qt Designer. This is a very powerful and popular combination for creating professional-looking desktop applications.

python qt designer-图1
(图片来源网络,侵删)

Here's a complete guide covering what it is, why you should use it, and a step-by-step tutorial.


What is Qt Designer?

Qt Designer is a visual tool for designing and building graphical user interfaces (GUIs) from Qt components. It's part of the Qt framework.

Think of it like a "drag-and-drop" interface builder for Qt. You can:

  • Drag and drop widgets (like buttons, labels, text boxes, etc.) onto a form.
  • Arrange them using layouts (horizontal, vertical, grid, etc.) to make them resize correctly.
  • Set properties for each widget (text, size, colors, etc.).
  • Create complex dialogs and main windows without writing a single line of C++ or Python code.

The output of Qt Designer is a .ui file, which is an XML-based description of your user interface.


Why Use Qt Designer with Python? (The Big Picture)

Instead of writing GUI code manually (e.g., button = QPushButton("Click Me")), you can use Qt Designer to create the layout visually. This approach has several major advantages:

  1. Separation of Concerns: You separate the UI design from the application logic (the Python code that makes the UI do things). This makes your code cleaner, easier to read, and easier to maintain.
  2. Rapid Prototyping: You can quickly create and modify UI layouts without constantly recompiling or running your Python script.
  3. Collaboration: Designers can create the UI, and developers can implement the functionality, without stepping on each other's toes.
  4. Professional Look: Qt provides a set of high-quality, native-looking widgets that can be easily styled.

The Workflow: From .ui File to Running App

The process looks like this:

  1. Design: Use Qt Designer to create a .ui file.
  2. Convert: Use a Python tool (pyuic) to convert the .ui file into a Python module (.py).
  3. Integrate: In your main Python script, import the generated module and "use" the UI you designed.
  4. Connect: Write Python functions (called "slots") and connect them to the signals from your widgets (e.g., a button's clicked signal).

Step-by-Step Tutorial: Building a Simple App

Let's build a simple application that has a line edit, a button, and a label. When you type a name and click the button, the label will display a greeting.

Step 1: Prerequisites

First, you need to install the necessary libraries. The most common one is PyQt5.

pip install PyQt5

This will install both PyQt5 (the Python bindings for Qt) and pyqt5-tools, which includes the pyuic conversion tool.

Step 2: Design the UI with Qt Designer

  1. Launch Qt Designer:

    • On Windows, you can find it in the Start Menu after installing PyQt5.
    • On macOS/Linux, you can often run it from the command line: designer
  2. Create a New Form:

    • When Qt Designer starts, you'll see a "New Form" dialog.
    • Choose "Main Window" and click "Create". This gives us a standard application window with a menu bar, toolbar, and status bar, which is a great starting point.
  3. Build the Layout:

    • Drag Widgets: From the "Widget Box" on the left, drag a QLabel, a QLineEdit, and a QPushButton onto the central area of the main window.
    • Use Layouts: This is the most important step for a responsive UI.
      • Select all three widgets (hold Ctrl or Cmd and click them).
      • Right-click on the selected widgets and go to Lay Out -> Layout Vertically. The designer will automatically arrange them in a column.
      • Now, select the entire vertical layout and use the "Lay Out" tool in the toolbar to Lay Out Horizontally in the Available Space. This makes the layout expand to fill the window.
  4. Set Widget Properties:

    • Click on the QLabel. In the "Property Editor" on the right, find the text property and change it to something like "Enter your name:".
    • Click on the QPushButton. Change its text property to "Say Hello".
    • Click on the other QLabel (the one that will display the greeting). Clear its text property. You can also give it an objectName to make it easier to reference later. Let's call it greeting_label.
  5. Save the UI File:

    • Go to File -> Save As...
    • Save it as main_window.ui in your project folder.

Your .ui file is now complete! It's just an XML file that describes your window and all its widgets.

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

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

  1. Open your command prompt or terminal.

  2. Navigate to your project folder.

  3. Run the pyuic command:

    pyuic5 -x main_window.ui -o main_window_ui.py
    • -x or --from-imports: This flag adds the necessary from PyQt5 import ... lines to the top of the file, making it easier to use.
    • main_window.ui: Your source UI file.
    • -o or --output: Specifies the output Python file.
    • main_window_ui.py: The generated Python module.

If you open main_window_ui.py, you'll see a lot of code defining a class Ui_MainWindow that contains all your widgets as attributes (e.g., self.pushButton, self.greeting_label).

Step 4: Write the Python Application Logic

Now, create a new Python file in the same folder, let's call it app.py. This is where you'll bring the UI to life.

import sys
from PyQt5.QtWidgets import QApplication, QMainWindow
# Import the UI class that we generated
from main_window_ui import Ui_MainWindow
class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        # Create an instance of the UI
        self.ui = Ui_MainWindow()
        # Setup the UI from the generated file
        self.ui.setupUi(self)
        # --- Connect signals and slots ---
        # Connect the button's 'clicked' signal to our custom slot method
        self.ui.say_hello_button.clicked.connect(self.show_greeting)
    def show_greeting(self):
        """This is our 'slot' or callback function."""
        name = self.ui.name_line_edit.text()
        if name:
            self.ui.greeting_label.setText(f"Hello, {name}!")
        else:
            self.ui.greeting_label.setText("Please enter a name.")
if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())

Explanation of app.py:

  1. MainWindow(QMainWindow): We create our main application window by subclassing QMainWindow.
  2. self.ui = Ui_MainWindow(): We create an instance of the UI class generated by pyuic5.
  3. self.ui.setupUi(self): This is the magic line. It takes the UI definition and "applies" it to our MainWindow instance. After this, all the widgets from your .ui file are accessible as attributes of self.ui (e.g., self.ui.name_line_edit).
  4. self.ui.say_hello_button.clicked.connect(self.show_greeting): This is the core of event-driven programming.
    • Signal: clicked is a signal that a QPushButton emits when it's clicked.
    • Slot: self.show_greeting is our custom method (a "slot").
    • connect(): This function links the signal to the slot. Now, whenever the button is clicked, the show_greeting method will be called.
  5. show_greeting(): This method gets the text from the QLineEdit, formats it, and sets the text of the QLabel.

Step 5: Run the Application

You're all set! Run your application from the terminal:

python app.py

You should see your window pop up. Type a name into the line edit, click the button, and watch the label update!


Advanced Topic: Loading .ui Files at Runtime (More Flexible)

The method above requires you to run pyuic every time you change the design. A more flexible approach is to load the .ui file directly at runtime using QUiLoader. This is the modern recommended way.

Here's how you would modify app.py:

import sys
from PyQt5.QtWidgets import QApplication, QMainWindow
from PyQt5 import uic # Import the uic module
# We no longer need to import the generated .py file
class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        # Load the UI file directly
        uic.loadUi("main_window.ui", self)
        # --- Connect signals and slots ---
        # The rest of the code is exactly the same!
        self.ui.say_hello_button.clicked.connect(self.show_greeting)
    def show_greeting(self):
        name = self.ui.name_line_edit.text()
        if name:
            self.ui.greeting_label.setText(f"Hello, {name}!")
        else:
            self.ui.greeting_label.setText("Please enter a name.")
if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())

Pros of this method:

  • No pyuic step: You just edit main_window.ui in Qt Designer and save it. The next time you run app.py, the new design is automatically loaded.
  • Cleaner project: You don't have an extra generated .py file to manage.

Cons:

  • Can be slightly slower at startup as the XML file needs to be parsed.
  • Some advanced features might be less accessible compared to the compiled Python module.

For most projects, loading at runtime is the preferred approach.

分享:
扫描分享到社交APP
上一篇
下一篇