基于Qt Designer 的信号与槽
可以使用 Qt Designer 创建信号与槽,这种方式的好处是可以可视化创建页面视图,少写很多代码,只需要关注逻辑部分就可以。
本节案例要实现的功能如下:
通过一个模拟打印的界面来详细说明信号的使用,在打印时可以设置打印的份数、纸张类型,触发"打印"按钮后,将执行结果显示在右侧
通过 QCheckBox("全屏预览"复选框)来选择是否通过全屏模式进行预览,并将执行结果显示在右侧。
按F1键可以显示 helpMessage 信息。
使用 Qt Designer 新建一个模板名为 Widget 的简单窗口,该窗口的文件名为MainWinSigmalSlogui。将 Widget Box 窗格的控件拖曳到窗口中,实现的界面效果如图所示。
为了使窗口的显示和业务逻辑分离,需要新建一个调用窗口显示的文件MainWinSignalSlogRun.py,在调用类中添加多个自定义信号,并与槽函数进行绑定
代码如下:
# -*- coding: utf-8 -*-
import sys
from PySide6.QtWidgets import QApplication,QMainWindow
from MainWinSignalSlog import Ui_Form
from PySide6.QtCore import Signal,Qt
class MyMainWindow(QMainWindow,Ui_Form):
helpSignal = Signal(str)
printSignal = Signal(list)
# 声明一个多重载版本的信号,包括了一个带int和str类型参数的信号,以及带str参数的信号
previewSignal = Signal([int,str],[str])
def __init__(self,parent=None):
super(MyMainWindow,self).__init__(parent)
self.setupUi(self)
self.initUI()
def initUI(self):
self.helpSignal.connect(self.showHelpMessage)
self.printSignal.connect(self.printPaper)
self.previewSignal[str].connect(self.previewPaper)
self.previewSignal[int,str].connect(self.previewPaperWithArgs)
self.printButton.clicked.connect(self.emitPrintSignal)
# self.previewButton.clicked.connect(self.emitPreviewSignal)
# 发射预览信号
def emitPreviewSignal(self):
if self.previewStatus.isChecked()== True:
self.previewSignal[int,str].emit(1080,"Full Screen")
elif self.previewStatus.isChecked()== False:
self.previewSignal[str].emit("Preview")
# 发射打印信号
def emitPrintSignal(self):
pList = []
pList.append(self.numberSpinBox.value())
pList.append(self.styleCombo.currentText())
self.printSignal.emit(pList)
def printPaper(self,list):
self.resultLabel.setText("打印:"+"份数:"+ str(list[0])+"纸张:"+ str(list[1]))
def previewPaperWithArgs(self,style,text):
self.resultLabel.setText(str(style)+ text)
def previewPaper(self,text):
self.resultLabel.setText(text)
# 重载点击键盘事件
def keyPressEvent(self,event):
if event.key()== Qt.Key_F1:
self.helpSignal.emit("help message")
# 显示帮助消息
def showHelpMessage(self,message):
self.resultLabel.setText(message)
self.statusBar().showMessage(message)
if __name__ =="__main__":
app = QApplication(sys.argv)
win = MyMainWindow()
win.show()
sys.exit(app.exec())
MainWinSignalSlog.py
# -*- coding: utf-8 -*-
################################################################################
## Form generated from reading UI file 'MainWinSignalSlog.ui'
##
## Created by: Qt User Interface Compiler version 6.2.3
##
## WARNING! All changes made in this file will be lost when recompiling UI file!
################################################################################
from PySide6.QtCore import(QCoreApplication,QDate,QDateTime,QLocale,
QMetaObject,QObject,QPoint,QRect,
QSize,QTime,QUrl,Qt)
from PySide6.QtGui import(QBrush,QColor,QConicalGradient,QCursor,
QFont,QFontDatabase,QGradient,QIcon,
QImage,QKeySequence,QLinearGradient,QPainter,
QPalette,QPixmap,QRadialGradient,QTransform)
from PySide6.QtWidgets import(QApplication,QCheckBox,QComboBox,QGroupBox,
QHBoxLayout,QLabel,QPushButton,QSizePolicy,
QSpinBox,QWidget)
class Ui_Form(object):
def setupUi(self,Form):
if not Form.objectName():
Form.setObjectName(u"Form")
Form.resize(715,225)
self.controlsGroup = QGroupBox(Form)
self.controlsGroup.setObjectName(u"controlsGroup")
self.controlsGroup.setGeometry(QRect(10,20,451,151))
self.layoutWidget = QWidget(self.controlsGroup)
self.layoutWidget.setObjectName(u"layoutWidget")
self.layoutWidget.setGeometry(QRect(10,40,411,30))
self.horizontalLayout = QHBoxLayout(self.layoutWidget)
self.horizontalLayout.setObjectName(u"horizontalLayout")
self.horizontalLayout.setContentsMargins(0,0,0,0)
self.label = QLabel(self.layoutWidget)
self.label.setObjectName(u"label")
self.horizontalLayout.addWidget(self.label)
self.numberSpinBox = QSpinBox(self.layoutWidget)
self.numberSpinBox.setObjectName(u"numberSpinBox")
self.horizontalLayout.addWidget(self.numberSpinBox)
self.styleCombo = QComboBox(self.layoutWidget)
self.styleCombo.addItem("")
self.styleCombo.addItem("")
self.styleCombo.addItem("")
self.styleCombo.setObjectName(u"styleCombo")
self.horizontalLayout.addWidget(self.styleCombo)
self.label_2 = QLabel(self.layoutWidget)
self.label_2.setObjectName(u"label_2")
self.horizontalLayout.addWidget(self.label_2)
self.printButton = QPushButton(self.layoutWidget)
self.printButton.setObjectName(u"printButton")
self.horizontalLayout.addWidget(self.printButton)
self.layoutWidget1 = QWidget(self.controlsGroup)
self.layoutWidget1.setObjectName(u"layoutWidget1")
self.layoutWidget1.setGeometry(QRect(10,100,201,30))
self.horizontalLayout_2 = QHBoxLayout(self.layoutWidget1)
self.horizontalLayout_2.setObjectName(u"horizontalLayout_2")
self.horizontalLayout_2.setContentsMargins(0,0,0,0)
self.previewStatus = QCheckBox(self.layoutWidget1)
self.previewStatus.setObjectName(u"previewStatus")
self.horizontalLayout_2.addWidget(self.previewStatus)
self.previewButton = QPushButton(self.layoutWidget1)
self.previewButton.setObjectName(u"previewButton")
self.horizontalLayout_2.addWidget(self.previewButton)
self.resultGroup = QGroupBox(Form)
self.resultGroup.setObjectName(u"resultGroup")
self.resultGroup.setGeometry(QRect(470,20,231,151))
self.resultLabel = QLabel(self.resultGroup)
self.resultLabel.setObjectName(u"resultLabel")
self.resultLabel.setGeometry(QRect(20,30,191,101))
self.retranslateUi(Form)
self.previewButton.clicked.connect(Form.emitPreviewSignal)
QMetaObject.connectslotsByName(Form)
# setupUi
def retranslateUi(self,Form):
Form.setWindowTitle(QCoreApplication.translate("Form",u"\u6253\u5370\u63a7\u4ef6",None))
self.controlsGroup.setTitle(QCoreApplication.translate("Form",u"\u6253\u5370\u63a7\u5236",None))
self.label.setText(QCoreApplication.translate("Form",u"\u6253\u5370\u4efd\u6570:",None))
self.styleCombo.setItemText(0,QCoreApplication.translate("Form",u"A3",None))
self.styleCombo.setItemText(1,QCoreApplication.translate("Form",u"A4",None))
self.styleCombo.setItemText(2,QCoreApplication.translate("Form",u"A5",None))
self.label_2.setText(QCoreApplication.translate("Form",u"\u7eb8\u5f20\u7c7b\u578b:",None))
self.printButton.setText(QCoreApplication.translate("Form",u"\u6253\u5370",None))
self.previewStatus.setText(QCoreApplication.translate("Form",u"\u5168\u5c4f\u9884\u89c8",None))
self.previewButton.setText(QCoreApplication.translate("Form",u"\u9884\u89c8",None))
self.resultGroup.setTitle(QCoreApplication.translate("Form",u"\u64cd\u4f5c\u7ed3\u679c",None))
self.resultLabel.setText(QCoreApplication.translate("Form",u"<html><head/><body><p><br/></p></body></html>",None))
# retranslateUi
在MainWinSignalSlogRun.py 文件中,并没有把 previewButton 按钮和emitPreviewSignal()槽函数连接起来,实际上它们却连接成功,这主要是因为使用 Qt Designer添加了自定义信号与槽.
需要注意的是,当这里的目标控件为主窗口时才可以使用自定义槽函数。先通过这种方式添加自定义槽函数,然后通过 pyside6-uic 转换成MainWinSignalSlog.py 文件,在这个文件中88行可以看到如下代码:
self.previewButton.clicked.connect(Form.emitPreviewSignal)
可以看到,在MainWinSignalSlog.py 文件中已经定义了 clicked 信号与槽函数emitPreviewSignal()的绑定,因此在MainWinSignalSlogRunpy 文件中可以运行。
这种方式的逻辑比较麻烦,因为 Form.emitPreviewSignal 调用的实际上是子类的方法,而这个方法对于Form本身来说是不存在的。也就是说,它调用了一个不存在的方法逻辑不通。对于这行代码,在MainWinSignalSlogRunpy 文件中定义也是一样的,逻辑上会更顺畅一些。总的来说,不太推荐使用 Qt Designer 来添加自定义信号与槽函数,建议在它的启动文件中添加。