Python PyQt

Windows, layouts, signals and slots, and packaging to an exe.

Advanced
Key PointsQt uses signals and slots instead of callbacks — connect a widget signal to a Python method and the event loop does the rest.

Minimal Window

Every PyQt6 app is three steps: create QApplication, build the window, call app.exec(). Without the last step the window flashes and exits.

Bash
pip install PyQt6
Python
import sys
from PyQt6.QtWidgets import QApplication, QLabel, QWidget, QVBoxLayout

app = QApplication(sys.argv)

win = QWidget()
win.setWindowTitle("BackendWiki")
layout = QVBoxLayout(win)
layout.addWidget(QLabel("Hello, PyQt6"))
win.resize(320, 160)
win.show()

sys.exit(app.exec())
Output
# 弹出一个 320x160 的窗口,显示 Hello, PyQt6

Signals and Slots

A button emits clicked; connect() wires it to your function. clicked passes a checked boolean.

Python
from PyQt6.QtWidgets import QPushButton, QLineEdit, QVBoxLayout, QWidget

class Panel(QWidget):
    def __init__(self):
        super().__init__()
        self.input = QLineEdit(placeholderText="输入点什么")
        self.btn = QPushButton("回显")
        self.out = QLineEdit(readOnly=True)

        lay = QVBoxLayout(self)
        for w in (self.input, self.btn, self.out):
            lay.addWidget(w)

        self.btn.clicked.connect(self.on_click)

    def on_click(self, checked=False):
        self.out.setText(self.input.text().upper())
Output
# 点击「回显」后,下方输入框显示大写文本

Layouts

LayoutBehaviour
QVBoxLayoutStack vertically
QHBoxLayoutStack horizontally
QGridLayoutRow/column grid
QFormLayoutLabel + field rows

Packaging

Bash
pip install pyinstaller
pyinstaller --noconsole --onefile main.py
# 产物:dist/main.exe
--onefile extracts to a temp dir on every launch, so startup is slow. Use --onedir when that matters.

Friends & Partners