"""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 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:actual offscreen widgets and events, non-native file dialogs, local UTF-8 I/O
入口文件:projects/python-lab/python-pyqt.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
python-pyqt.py,或下载右侧课程工程包。 - 确认本地已准备 actual offscreen widgets and events, non-native file dialogs, local UTF-8 I/O。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联82章) · 含当前章节或实例 · mbskycom202611a463.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a297.zip
课程关联工程包(登记关联82章) · 含当前章节或实例 · mbskycom202612a292.zip