蓝色天空网mbsky.com · 知识 · 实践 · 创造Python · 本地阅读预览
教程 / Python / 数据科学 / Python

Python PyQt:桌面控件、信号与记事本

从窗口和布局开始,用实际按钮、输入、文件操作和菜单完成一个桌面记事本。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

应用对象、版本和基础窗口

PyQt 是 Qt 的 Python 绑定。PyQt4 对应已停用维护的 Qt4,PyQt5 对应 Qt5,PyQt6 对应 Qt6。也可使用 Python 自带的 Tkinter 做不同技术栈的桌面程序。

本实验使用 CPython 3.12 与 PyQt6 6.9.1,可在隔离环境中安装指定版本。旧版 PyQt5 的 app.exec_() 在 PyQt6 改用 app.exec()。枚举常需写完整范围,例如 Qt.WidgetAttribute.WA_DeleteOnClose。QAction 在 PyQt6 从 QtGui 导入。 本站用两个独立环境运行同一份表单,验证 PyQt5 5.15.11 与 PyQt6 6.9.1 的事件循环、按钮、工具栏动作和关闭后销毁。解压后在安装对应绑定的环境运行 python pyqt-lab/migration_demo.py 5 或 python pyqt-lab/migration_demo.py 6。PyQt5 分支从 QtWidgets 导入 QAction,使用 Qt.WA_DeleteOnClose 和 exec_()。PyQt6 分支采用上文的新写法。

创建一个 QApplication 后再创建 QWidget。设置标题和几何尺寸,show 显示窗口,exec 开始处理事件。实验保留一个空窗口作为第一步,并检查关闭后对象销毁的条件。

本站 Qt 离屏插件显示的 440×210 基础窗口内容区。窗口标题与销毁已另外实测。
本站 Qt 离屏插件显示的 440×210 基础窗口内容区。窗口标题与销毁已另外实测。

用控件、布局与信号搭建表单

需要菜单和中央控件时用 QMainWindow。把 QLineEdit、QLabel 和 QPushButton 放进中央 QWidget 的布局。可用 move 和 setGeometry 演示手工定位。窗口尺寸变化时,用 QVBoxLayout、QHBoxLayout、QGridLayout 或 QFormLayout 管理位置更稳妥。

在本站表单输入地点后点击按钮,clicked 触发槽读取 QLineEdit 并更新 QLabel。不要用连接时调用槽的结果代替槽本身。自定义信号用 QObject 子类的类属性 pyqtSignal(str) 声明,再用 emit 传递字符串。

同一按钮有时可连接多个槽。先验证输出变化,再按需要控制连接范围。表单截图展示本站的实测输入和反馈。

本站表单收到 North 后,按钮点击使标签显示已登记 North。
本站表单收到 North 后,按钮点击使标签显示已登记 North。

设计器文件与生成代码

Qt Widgets Designer 可用来编辑 .ui 文件。程序可用 uic.loadUiType 读取 .ui,也可用 pyuic5 或 pyuic6 按相同主版本生成 Python 文件。loadUiType 的输入是 .ui 文件,生成的 .py 文件则用 import。本站用自编的 .ui 测试两条路径。 在解压目录运行 python pyqt-lab/ui_workflow.py,可直接加载 panel.ui。运行 pyuic6 pyqt-lab/panel.ui -o pyqt-lab/generated_panel.py,再执行 python pyqt-lab/ui_workflow.py --generated,可使用生成的 Python 模块。本站修改临时 .ui 的标题和按钮文字后,重新打开的动态表单立即采用新文字。生成版本在重新运行 pyuic6 后才更新,两种表单均可输入地点并点击确认。 使用 PyQt5 时可执行 pyuic5 pyqt-lab/panel.ui -o pyqt-lab/generated_panel.py,再用 python pyqt-lab/generated_form.py 5 运行生成表单。PyQt6 对应使用 pyuic6 和参数 6。本站分别运行两代编译器,从同一 .ui 生成不同的 Python 文件,两份表单均能回显输入 F29。生成文件会导入对应版本的绑定,切换主版本时应从 .ui 重新生成。

Designer 与其他桌面工具的安装位置取决于发行方式,旧资料里的 PyQt5-tools 目录仅适用于相应安装。工具编辑界面和 PyQt5 运行结果要在对应环境验证。WebEngine 与 Charts 是独立扩展,PyQt6 用 PyQt6-WebEngine 和 PyQt6-Charts。 本站在 PyQt6 6.9.1 环境加装 PyQt6-Charts 6.9.0。运行 python pyqt-lab/charts_demo.py,可显示班次折线图。点击添加班次,第四个数据点与横轴范围随之更新。点击重置恢复原始三个点。Qt Charts 自 Qt 6.10 起已弃用。维护既有代码时可参考此例,Qt 官方为新项目推荐 Qt Graphs。 安装 PyQt6-WebEngine 后,运行 python pyqt-lab/webengine_demo.py 可在 QWebEngineView 中打开随包提供的本地页面。输入线路并点击确认,页面脚本会更新结果。用 loadFinished 判断加载是否成功,文件缺失会进入失败分支。该示例的请求拦截器仅允许指定目录中的本地文件和控件所需的内部资源。

用菜单完成本地记事本

用 QTextEdit 作为中央控件,菜单里的新建、打开、保存、退出和编辑动作都由 QAction 触发。把动作放进菜单和工具栏,可共用同一快捷键和处理函数。

对话框返回空路径表示取消。实验用非原生文件对话框打开临时 UTF-8 文件、修改并保存,然后比较字节。读取内容用 setPlainText 保留尖括号和换行。文件错误用 QMessageBox 提示,撤销、剪切、复制和粘贴由编辑控件处理。

本站记事本保存 UTF-8 文档后的状态栏、菜单、工具栏与编辑内容。
本站记事本保存 UTF-8 文档后的状态栏、菜单、工具栏与编辑内容。

布局表下方的组件说明可用于选型。QListWidget、QTableWidget、QTreeWidget 直接管理条目,QListView、QTableView、QTreeView 要绑定数据模型。系统托盘是否可用取决于桌面环境。 运行 pyqt-lab/tray_demo.py 可在支持托盘的桌面上添加图标,通过菜单打开状态窗口或退出。程序先调用 isSystemTrayAvailable() 检查环境。本站在 Windows 上观察到 show() 后图标有有效的屏幕区域,hide() 后该区域消失,并点击本站菜单验证状态窗口可以打开。

下载工程并复跑 GUI

下载 ZIP 后保留 pyqt-lab/panel.ui。安装 PyQt6 6.9.1 后执行 python python-pyqt.py 打开记事本,执行 python python-pyqt.py --verify 可复跑自动化操作。该模式使用 Qt 的离屏插件,不需要可见桌面。 在 Windows 桌面中执行 python pyqt-lab/native_dialog.py,可用系统文件对话框选择 UTF-8 文本,再另存一份。打开或保存时取消会结束相应操作。本站用 Windows 原生对话框实际确认文件名,核对了取消时不创建文件,以及打开和另存后 UTF-8 字节与换行完全一致。

下载本站 PyQt 实验 ZIP

所需环境:CPython 3.12 与 PyQt6 6.9.1

ZIP SHA256:6d92a63fd080d371a18f795350c0bd0eb84c72a66074a8e669d10b817d82e0c0

常用控件与模块

组件PyQt6 模块作用和条件
QWidgetQtWidgets基础窗口或子控件容器,可设置标题和可见性。
QMainWindowQtWidgets为中央控件、菜单、工具栏与状态栏提供区域。
QDialogQtWidgets可运行独立对话流程,返回接受或拒绝。
QVBoxLayoutQtWidgets按垂直方向排列子控件。
QHBoxLayoutQtWidgets按水平方向排列子控件。
QGridLayoutQtWidgets按行、列和可选跨度管理子控件。
QFormLayoutQtWidgets用标签与输入字段构成成对行。
QPushButtonQtWidgets触发命令,常用 clicked 信号。
QRadioButtonQtWidgets表示一组选项中的单选项。
QCheckBoxQtWidgets表达可独立切换的勾选状态。
QToolButtonQtWidgets适合工具栏的紧凑按钮,也可绑定 QAction。
QLineEditQtWidgets编辑一行文本,可接收键盘输入。
QTextEditQtWidgets编辑多行文本,支持富文本与 HTML 子集。
QPlainTextEditQtWidgets处理不含富文本格式的多行文档。
QSpinBoxQtWidgets在整数范围内输入或调节数值。
QDoubleSpinBoxQtWidgets按设定精度和范围处理小数。
QComboBoxQtWidgets从下拉选项中选择,可读取当前文本或索引。
QDateEditQtWidgets编辑日期值。
QTimeEditQtWidgets编辑时刻值。
QDateTimeEditQtWidgets同时编辑日期和时刻。
QSliderQtWidgets沿水平或垂直轨道调整整数值。
QDialQtWidgets在旋钮界面中调整整数值。
QLabelQtWidgets显示文本或像素图。
QLCDNumberQtWidgets以数字显示样式呈现数值。
QProgressBarQtWidgets用范围和当前值表示进度。
QStatusBarQtWidgets显示主窗口的即时状态或常驻控件。
QGroupBoxQtWidgets用标题组织一组子控件,可选勾选状态。
QTabWidgetQtWidgets以页签在多个页面之间切换。
QStackedWidgetQtWidgets一次显示一页,由程序决定切换方式。
QScrollAreaQtWidgets给超出显示范围的子控件提供滚动视口。
QMdiAreaQtWidgets在同一工作区组织多个内部窗口。
QListWidgetQtWidgets带内建项容器的列表。
QTreeWidgetQtWidgets带内建项容器的层级树。
QTableWidgetQtWidgets带内建项容器的行列表格。
QListViewQtWidgets以列表方式显示外部模型。
QTableViewQtWidgets按表格显示外部模型。
QTreeViewQtWidgets按层级显示外部模型。
QMenuBarQtWidgets组织主窗口的顶层菜单。
QMenuQtWidgets排列可触发的菜单项,可含子菜单。
QToolBarQtWidgets让用户从工具栏触发常用动作。
QActionQtGui封装可复用的命令、快捷键与触发信号。PyQt6 在 QtGui 中导入。
QFileDialogQtWidgets选择要读取或保存的本地路径,可使用非原生实现。
QColorDialogQtWidgets选择颜色,可读取当前值或确认值。
QFontDialogQtWidgets选择字体,可读取字号等属性。
QInputDialogQtWidgets提示用户输入文本、整数或小数等值。
QMessageBoxQtWidgets显示信息、警告或确认请求。
QGraphicsViewQtWidgets负责显示并浏览二维场景。
QGraphicsSceneQtWidgets维护二维图元,并提供查找与选择接口。
QCalendarWidgetQtWidgets显示日历并保存选中的日期。
QSplashScreenQtWidgets在应用启动期间显示临时画面和消息。
QSystemTrayIconQtWidgets提供托盘图标和通知接口,须由桌面环境支持。
QWebEngineViewQtWebEngineWidgets嵌入网页视图。PyQt6 对应独立的 PyQt6-WebEngine 包,须另行验证网页加载。

本章自编源码与运行范围

Python · 阅读源码
"""Owned PyQt6 exercises. A normal run opens the notepad; --verify runs the GUI checks."""
import argparse
import io
import json
import os
from pathlib import Path
import sys
from tempfile import TemporaryDirectory
import traceback

parser = argparse.ArgumentParser()
parser.add_argument('--verify', action='store_true')
parser.add_argument('--private-site', type=Path)
parser.add_argument('--screenshots', type=Path)
options = parser.parse_args()
if options.private_site:
    sys.path.insert(0, str(options.private_site.resolve(strict=True)))
if options.verify:
    os.environ['QT_QPA_PLATFORM'] = 'offscreen'

from PyQt6 import QtCore as C, QtGui as G, QtWidgets as W, uic
from PyQt6.QtTest import QTest

CLICK = C.Qt.MouseButton.LeftButton
PROJECT = Path(__file__).resolve().parent / 'pyqt-lab'


class StationSignal(C.QObject):
    changed = C.pyqtSignal(str)


class Notepad(W.QMainWindow):
    def __init__(self, verify=False):
        super().__init__()
        self.verify = verify
        self.setWindowTitle('蓝色天空网 · 调度记事本')
        self.resize(640, 400)
        self.editor = W.QTextEdit()
        self.setCentralWidget(self.editor)
        self.statusBar().showMessage('准备编辑')
        self.actions = {}
        file_menu = self.menuBar().addMenu('文件')
        edit_menu = self.menuBar().addMenu('编辑')
        bar = self.addToolBar('文件操作')
        for key, title, shortcut, command, menu in (
            ('new', '新建', 'Ctrl+N', self.editor.clear, file_menu),
            ('open', '打开', 'Ctrl+O', self.open_file, file_menu),
            ('save', '保存', 'Ctrl+S', self.save_file, file_menu),
            ('quit', '退出', 'Ctrl+Q', self.close, file_menu),
            ('copy', '复制', 'Ctrl+C', self.editor.copy, edit_menu),
            ('cut', '剪切', 'Ctrl+X', self.editor.cut, edit_menu),
            ('paste', '粘贴', 'Ctrl+V', self.editor.paste, edit_menu),
            ('undo', '撤销', 'Ctrl+Z', self.editor.undo, edit_menu),
        ):
            action = G.QAction(title, self)
            action.setShortcut(G.QKeySequence(shortcut))
            action.triggered.connect(command)
            self.actions[key] = action
            menu.addAction(action)
            if key in ('new', 'open', 'save'):
                bar.addAction(action)

    def choose_file(self, saving):
        dialog = W.QFileDialog(self, '保存调度记录' if saving else '打开调度记录')
        if self.verify:
            dialog.setOption(W.QFileDialog.Option.DontUseNativeDialog)
        if saving:
            dialog.setAcceptMode(W.QFileDialog.AcceptMode.AcceptSave)
            dialog.setFileMode(W.QFileDialog.FileMode.AnyFile)
        else:
            dialog.setFileMode(W.QFileDialog.FileMode.ExistingFile)
        if dialog.exec() == W.QDialog.DialogCode.Accepted:
            return Path(dialog.selectedFiles()[0])
        return None

    def open_file(self):
        path = self.choose_file(False)
        if path is not None:
            try:
                self.editor.setPlainText(path.read_text(encoding='utf-8'))
            except (OSError, UnicodeError) as error:
                W.QMessageBox.warning(self, '读取失败', str(error))
            else:
                self.statusBar().showMessage('已读取 UTF-8 文件')

    def save_file(self):
        path = self.choose_file(True)
        if path is not None:
            try:
                path.write_bytes(self.editor.toPlainText().encode('utf-8'))
            except OSError as error:
                W.QMessageBox.warning(self, '保存失败', str(error))
            else:
                self.statusBar().showMessage('已保存 UTF-8 文件')


def verify(app, report, screenshots):
    def check(name, actual, expected, inputs, operation):
        if actual != expected:
            raise AssertionError((name, actual, expected))
        report.append(dict(name=name, actual=actual, expected=expected,
                           inputs=inputs, operation=operation, passed=True))

    def capture(widget, filename):
        if screenshots:
            app.processEvents()
            if not widget.grab().save(str(screenshots / filename), 'PNG'):
                raise RuntimeError('Could not capture widget: '+filename)

    window = W.QWidget()
    window.setWindowTitle('蓝色天空网 · 窗口起步')
    window.resize(440, 210)
    window.setAttribute(C.Qt.WidgetAttribute.WA_DeleteOnClose, True)
    destroyed = []
    window.destroyed.connect(lambda: destroyed.append(True))
    window.show()
    capture(window, '01-window.png')
    check('QWidget', [window.windowTitle(), window.width(), window.height(), window.isVisible()],
          ['蓝色天空网 · 窗口起步',440,210,True], '440×210 QWidget', 'Show a sized top-level window')
    window.close()
    C.QCoreApplication.sendPostedEvents(None, C.QEvent.Type.DeferredDelete)
    check('QApplication lifecycle and delete on close',[W.QApplication.instance() is app,destroyed],
          [True,[True]], 'single QApplication and widget attribute', 'Close the window and deliver deletion event')

    form = W.QMainWindow()
    form.setWindowTitle('蓝色天空网 · 地点登记')
    form.resize(490, 230)
    central = W.QWidget()
    form.setCentralWidget(central)
    vertical = W.QVBoxLayout(central)
    label = W.QLabel('等待登记')
    line = W.QLineEdit()
    button = W.QPushButton('登记地点')
    vertical.addWidget(line)
    vertical.addWidget(button)
    vertical.addWidget(label)
    button.clicked.connect(lambda: label.setText('已登记 '+line.text()))
    form.show()
    QTest.keyClicks(line, 'North')
    QTest.mouseClick(button, CLICK)
    capture(form,'02-form.png')
    check('QMainWindow',form.centralWidget() is central,True,'central QWidget','Mount the form in the central area')
    check('QVBoxLayout',[vertical.itemAt(i).widget() is w for i,w in enumerate((line,button,label))],
          [True]*3,'input, button, label','Read the inserted widgets in vertical order')
    check('QLineEdit',line.text(),'North','North','Enter text with QTest key events')
    check('QPushButton',label.text(),'已登记 North','one button click','Send a QTest click and read its slot output')
    check('QLabel',label.text(),'已登记 North','the form output','Read text displayed by the label')
    emitter = StationSignal()
    messages = []
    emitter.changed.connect(messages.append)
    emitter.changed.emit('North-02')
    check('custom typed signal',messages,['North-02'],'string payload','Emit and receive the typed signal')
    ui_file = PROJECT/'panel.ui'
    ui_type, base_type = uic.loadUiType(str(ui_file))
    designed = base_type()
    panel = ui_type()
    panel.setupUi(designed)
    with io.StringIO() as generated:
        uic.compileUi(str(ui_file),generated)
        namespace = {}
        exec(compile(generated.getvalue(),'<owned-generated-ui>','exec'),namespace)
    converted = base_type()
    compiled_panel = namespace['Ui_DispatchPanel']()
    compiled_panel.setupUi(converted)
    check('owned UI load and conversion',[panel.destination.placeholderText(),compiled_panel.submit.text()],
          ['填写目的地','登记'],'owned panel.ui','Load UI type, compile owned UI to Python, then set up both windows')

    dialog = W.QDialog()
    C.QTimer.singleShot(0, dialog.accept)
    check('QDialog',dialog.exec()==W.QDialog.DialogCode.Accepted,True,'queued accept callback',
          'Run its event loop and check the accepted result')
    row = W.QHBoxLayout()
    row.addWidget(W.QLabel('甲'))
    row.addWidget(W.QLabel('乙'))
    check('QHBoxLayout',[row.count(),row.itemAt(1).widget().text()],[2,'乙'],'two labels','Read positions in row order')
    grid = W.QGridLayout()
    grid.addWidget(W.QLabel('索引'),1,2)
    check('QGridLayout',grid.itemAtPosition(1,2).widget().text(),'索引',[1,2],'Look up a row and column')
    fields = W.QFormLayout()
    field = W.QLineEdit()
    fields.addRow('地点',field)
    check('QFormLayout',[fields.rowCount(),fields.labelForField(field).text()],[1,'地点'],'one label and input',
          'Find a label through the associated field')

    toggles = W.QWidget()
    left = W.QRadioButton('西',toggles)
    right = W.QRadioButton('东',toggles)
    left.setChecked(True)
    right.click()
    check('QRadioButton',[left.isChecked(),right.isChecked()],[False,True],'two radios sharing a parent','Switch the selected radio')
    box = W.QCheckBox('复核')
    box.click()
    check('QCheckBox',box.isChecked(),True,'initially unchecked','Click and read state')
    tool = W.QToolButton()
    tool_action = G.QAction('更新')
    fired = []
    tool_action.triggered.connect(lambda: fired.append('更新'))
    tool.setDefaultAction(tool_action)
    tool.click()
    check('QToolButton',fired,['更新'],'one QAction','Bind the action to the tool button and click')

    rich = W.QTextEdit()
    rich.setHtml('<b>重点</b>')
    check('QTextEdit',[rich.toPlainText(),'font-weight' in rich.toHtml()],['重点',True],
          '<b>重点</b>','Parse and inspect retained formatting')
    plain = W.QPlainTextEdit()
    plain.setPlainText('前站\n后站')
    check('QPlainTextEdit',plain.toPlainText(),'前站\n后站','two lines','Write and read pure text')
    spin = W.QSpinBox()
    spin.setRange(0,4)
    spin.setValue(9)
    check('QSpinBox',spin.value(),4,'9 in 0..4','Read the clamped integer')
    fraction = W.QDoubleSpinBox()
    fraction.setDecimals(2)
    fraction.setValue(2.376)
    check('QDoubleSpinBox',fraction.value(),2.38,'2.376 with two decimals','Read rounded fractional input')
    combo = W.QComboBox()
    combo.addItems(['西站','东站'])
    combo.setCurrentIndex(1)
    check('QComboBox',combo.currentText(),'东站',['西站','东站'],'Select the second option')
    date = C.QDate(2024,2,29)
    time = C.QTime(8,12)
    day = W.QDateEdit()
    day.setDate(date)
    check('QDateEdit',day.date().toString('yyyy-MM-dd'),'2024-02-29','leap day','Set and retrieve a date')
    clock = W.QTimeEdit()
    clock.setTime(time)
    check('QTimeEdit',clock.time().toString('HH:mm'),'08:12','08:12','Set and retrieve the time')
    calendar_time = W.QDateTimeEdit()
    calendar_time.setDateTime(C.QDateTime(date,time))
    check('QDateTimeEdit',calendar_time.dateTime().toString('yyyy-MM-dd HH:mm'),'2024-02-29 08:12',
          'date and time fixture','Read the combined date-time')
    for klass,value in ((W.QSlider,17),(W.QDial,39)):
        control = klass()
        control.setRange(0,100)
        control.setValue(value)
        control.triggerAction(W.QAbstractSlider.SliderAction.SliderSingleStepAdd)
        check(klass.__name__,control.value(),value+1,value,'Step once on an integer range')
    lcd = W.QLCDNumber()
    lcd.display(25)
    check('QLCDNumber',lcd.intValue(),25,25,'Display and read a number')
    progress = W.QProgressBar()
    progress.setRange(0,10)
    progress.setValue(7)
    check('QProgressBar',[progress.minimum(),progress.maximum(),progress.value()],[0,10,7],
          [0,10,7],'Set range and completion count')

    group = W.QGroupBox('批次')
    group.setCheckable(True)
    group.setChecked(False)
    check('QGroupBox',[group.title(),group.isChecked()],['批次',False],'checkable group','Read title and disabled group state')
    for klass in (W.QTabWidget,W.QStackedWidget):
        container = klass()
        one,two = W.QWidget(),W.QWidget()
        if isinstance(container,W.QTabWidget):
            container.addTab(one,'甲')
            container.addTab(two,'乙')
        else:
            container.addWidget(one)
            container.addWidget(two)
        container.setCurrentIndex(1)
        check(klass.__name__,container.currentWidget() is two,True,'two pages','Activate the second page')
    scroll = W.QScrollArea()
    contents = W.QLabel('可滚动内容')
    contents.setFixedSize(500,350)
    scroll.resize(160,100)
    scroll.setWidget(contents)
    scroll.show()
    app.processEvents()
    check('QScrollArea',scroll.verticalScrollBar().maximum()>0,True,'oversized label','Observe the visible scroll range')
    mdi = W.QMdiArea()
    mdi.addSubWindow(W.QLabel('批次 1'))
    check('QMdiArea',[sub.widget().text() for sub in mdi.subWindowList()],['批次 1'],
          'one internal window','Read the registered internal window')

    listing = W.QListWidget()
    listing.addItem('货架')
    check('QListWidget',listing.item(0).text(),'货架','one item','Read text from internal list')
    tree = W.QTreeWidget()
    parent = W.QTreeWidgetItem(tree,['主站'])
    W.QTreeWidgetItem(parent,['分站'])
    check('QTreeWidget',tree.topLevelItem(0).child(0).text(0),'分站','parent and child','Traverse the internal tree')
    table = W.QTableWidget(1,1)
    table.setItem(0,0,W.QTableWidgetItem('单元'))
    check('QTableWidget',table.item(0,0).text(),'单元','one cell','Read internal table item')
    model = G.QStandardItemModel()
    root = G.QStandardItem('主站')
    root.appendRow(G.QStandardItem('分站'))
    model.appendRow(root)
    for klass in (W.QListView,W.QTableView,W.QTreeView):
        view = klass()
        view.setModel(model)
        idx = view.model().index(0,0)
        text = idx.data()
        if isinstance(view,W.QTreeView):
            view.expand(idx)
            text = view.model().index(0,0,idx).data()
        check(klass.__name__,text,'分站' if isinstance(view,W.QTreeView) else '主站',
              'one QStandardItemModel','Bind the view to an external model and query the visible data')

    notebook = Notepad(verify=True)
    notebook.show()
    check('QMenuBar',[a.text() for a in notebook.menuBar().actions()],['文件','编辑'],'notepad menus','Inspect top-level menu actions')
    menu = notebook.menuBar().actions()[0].menu()
    check('QMenu',[a.text() for a in menu.actions()],['新建','打开','保存','退出'],'file menu','Read attached actions in order')
    bar = notebook.findChild(W.QToolBar)
    check('QToolBar',[a.text() for a in bar.actions()],['新建','打开','保存'],'file toolbar','Read reused actions')
    check('QAction',[notebook.actions['open'].shortcut().toString(),notebook.actions['open'] is menu.actions()[1]],
          ['Ctrl+O',True],'Open action','Read shortcut and shared identity')

    def select_file(path=None):
        modal = app.activeModalWidget()
        assert isinstance(modal,W.QFileDialog)
        if path is None:
            modal.reject()
        else:
            modal.setDirectory(str(path.parent))
            modal.selectFile(path.name)
            buttons = modal.findChild(W.QDialogButtonBox)
            QTest.mouseClick(buttons.button(W.QDialogButtonBox.StandardButton.Save if modal.acceptMode()==W.QFileDialog.AcceptMode.AcceptSave
                                            else W.QDialogButtonBox.StandardButton.Open), CLICK)

    with TemporaryDirectory(prefix='mbsky-pyqt-') as directory:
        folder = Path(directory)
        sample = folder/'dispatch.txt'
        saved = folder/'saved.txt'
        original = '<北站>\n任务:检查货架'
        sample.write_bytes(original.encode('utf8'))
        C.QTimer.singleShot(0,lambda: select_file(sample))
        notebook.actions['open'].trigger()
        check('QFileDialog',[notebook.editor.toPlainText(),notebook.statusBar().currentMessage()],
              [original,'已读取 UTF-8 文件'],'temporary UTF-8 file','Choose path in a real non-native dialog')
        notebook.editor.moveCursor(G.QTextCursor.MoveOperation.End)
        notebook.editor.insertPlainText('\n已复核')
        modified = original+'\n已复核'
        C.QTimer.singleShot(0,lambda: select_file(saved))
        notebook.actions['save'].trigger()
        capture(notebook,'03-notepad.png')
        check('notepad save writes UTF-8',saved.read_bytes().hex(),modified.encode('utf8').hex(),
              modified,'Choose save destination and read the actual bytes')
        check('QStatusBar',notebook.statusBar().currentMessage(),'已保存 UTF-8 文件','successful save','Read the resulting status')
        C.QTimer.singleShot(0,select_file)
        notebook.actions['open'].trigger()
        check('notepad cancel preserves text',notebook.editor.toPlainText(),modified,'reject the file dialog','Check current document remains')
        notebook.editor.selectAll()
        notebook.actions['copy'].trigger()
        notebook.actions['cut'].trigger()
        removed = notebook.editor.toPlainText()
        notebook.actions['paste'].trigger()
        pasted = notebook.editor.toPlainText()
        notebook.actions['undo'].trigger()
        undo = notebook.editor.toPlainText()
        notebook.actions['new'].trigger()
        check('notepad editing commands',[removed,pasted,undo,notebook.editor.toPlainText()],
              ['',modified,'',''],'selected document','Trigger copy, cut, paste, undo and new')
    notebook.actions['quit'].trigger()
    check('notepad quit closes window',not notebook.isVisible(),True,'quit action','Trigger quit and query visibility')

    color = W.QColorDialog(G.QColor('#103456'))
    check('QColorDialog',color.currentColor().name(),'#103456','#103456','Read the selected color')
    font_dialog = W.QFontDialog()
    available_font = font_dialog.currentFont()
    C.QTimer.singleShot(0,font_dialog.accept)
    font_accepted = font_dialog.exec() == W.QDialog.DialogCode.Accepted
    check('QFontDialog',[font_accepted,font_dialog.selectedFont()==available_font,available_font.pointSize()>0],
          [True,True,True],'the available offscreen font','Accept the dialog and compare the actual selected font')
    prompt = W.QInputDialog()
    prompt.setInputMode(W.QInputDialog.InputMode.IntInput)
    prompt.setIntValue(12)
    check('QInputDialog',prompt.intValue(),12,12,'Configure numeric input and read its value')
    message = W.QMessageBox(W.QMessageBox.Icon.Warning,'盘点','清单缺少编号',W.QMessageBox.StandardButton.Ok)
    C.QTimer.singleShot(0, lambda: QTest.mouseClick(message.button(W.QMessageBox.StandardButton.Ok),CLICK))
    check('QMessageBox',message.exec()==W.QMessageBox.StandardButton.Ok,True,'warning with OK','Click OK in the dialog')
    scene = W.QGraphicsScene()
    item = scene.addRect(0,0,20,10)
    view = W.QGraphicsView(scene)
    check('QGraphicsScene',scene.items()[0] is item,True,'one rectangle','Inspect the scene items')
    check('QGraphicsView',view.scene() is scene,True,'one scene','Inspect the view binding')
    calendar = W.QCalendarWidget()
    calendar.setSelectedDate(date)
    check('QCalendarWidget',calendar.selectedDate().toString('yyyy-MM-dd'),'2024-02-29','2024-02-29','Select a date')
    pixmap = G.QPixmap(80,40)
    pixmap.fill(G.QColor('#103456'))
    splash = W.QSplashScreen(pixmap)
    splash.showMessage('载入盘点表')
    check('QSplashScreen',splash.message(),'载入盘点表','loading message','Set and inspect the splash message')
    tray = W.QSystemTrayIcon()
    tray.setToolTip('盘点记录')
    check('QSystemTrayIcon configuration',tray.toolTip(),'盘点记录','offscreen plugin','Check tooltip configuration without a system tray')
    form.close()
    scroll.close()


def main():
    app = W.QApplication([sys.argv[0]])
    if not options.verify:
        window = Notepad()
        window.show()
        return app.exec()

    if sys.platform == 'win32':
        font = Path(os.environ.get('WINDIR','C:/Windows')) / 'Fonts/msyh.ttc'
        if font.is_file():
            font_id = G.QFontDatabase.addApplicationFont(str(font))
            families = G.QFontDatabase.applicationFontFamilies(font_id)
            if families:
                app.setFont(G.QFont(families[0], 10))
    app.setQuitOnLastWindowClosed(False)
    report, errors = [], []

    def run():
        try:
            verify(app, report, options.screenshots)
        except Exception:
            errors.append(traceback.format_exc())
        finally:
            app.quit()

    C.QTimer.singleShot(0,run)
    status = app.exec()
    if errors:
        raise RuntimeError(errors[0])
    assert status==0
    report.append(dict(name='Qt event loop exit', actual=status, expected=0, inputs='QTimer and QApplication.exec',
                       operation='Run and leave the real event loop', passed=True))
    print(json.dumps(dict(checks=report,pyqt=C.PYQT_VERSION_STR,qt=C.qVersion(),platform=app.platformName()),
                     ensure_ascii=False))
    return status


if __name__ == '__main__':
    raise SystemExit(main())
运行本章核心实例

所需环境:actual offscreen widgets and events, non-native file dialogs, local UTF-8 I/O

当前源码 SHA256:0710a0320ec1de9ff803b3eb8e094c2e5b9cc73f4fff2aad11d107873d2d62df

下载本站示例源码

当前源码有命名范围的实际运行记录;原文全部事实、其它平台和IDE界面仍待逐项验收。

常见错误与边界

  • 命令、源码、当前解释器和具体平台分别核对,不能以单项运行推断整章验收。

练习与解答

使用本站实例修改一个条件,先写下预期,再实际运行。

展开参考解答

比较原始输出、修改后的输出及错误类型;未执行的平台和界面继续单列。

规范与官方依据