七月
20
Pyside2教程:使用QtCore.Signal和QtCore.Slot案例
import sys
from PySide2 import QtWidgets as qtw
from PySide2 import QtGui as qtg
from PySide2 import QtCore as qtc
class FormWindow(qtw.QWidget):
# 自定义信号,这个信号携带的是string类型的数据。注意str是一个type object
# 在pyqt中,QtCore.Signal对应的函数为QtCore.pyqtSignal
# submitted = qtc.Signal(str)
# 用两个列表表示两种signature。一种只有一个str,另一种有int和str
submitted = qtc.Signal([str], [int, str])
def __init__(self):
super().__init__()
self.setLayout(qtw.QVBoxLayout())
self.edit = qtw.QLineEdit()
self.submit = qtw.QPushButton('提交', clicked=self.onSubmit)
self.layout().addWidget(self.edit)
self.layout().addWidget(self.submit)
@qtc.Slot()
def onSubmit(self):
# 调用自定义submitted信号的emit方法来定义信号施放的数据
if self.edit.text().isdigit():
text = self.edit.text()
# 注意这里在signal后面要用[]标记出对应的signature
self.submitted[int, str].emit(int(text), text)
else:
# 注意这里在signal后面要用[]标记出对应的signature
self.submitted[str].emit(self.edit.text())
self.close()
# 将主程序封装成类
class MainWindow(qtw.QWidget):
def __init__(self):
# 引入父类的__init__方法
super().__init__(parent=None)
# Main UI code goes here
self.setLayout(qtw.QVBoxLayout())
self.label = qtw.QLabel('点击"变"来改变文字')
self.change = qtw.QPushButton('变', clicked=self.onChange)
self.layout().addWidget(self.label)
self.layout().addWidget(self.change)
# End main UI code
# 显示主窗口
self.show()
@qtc.Slot()
def onChange(self):
self.formwindow = FormWindow()
# 注意这里在signal后面要用[]标记出对应的signature
self.formwindow.submitted[str].connect(self.onSubmittedStr)
# 注意这里在signal后面要用[]标记出对应的signature
self.formwindow.submitted[int, str].connect(self.onSubmittedIntStr)
self.formwindow.show()
@qtc.Slot(str)
def onSubmittedStr(self, string):
self.label.setText(string)
@qtc.Slot(int, str)
def onSubmittedIntStr(self, integer, string):
text = 'The string {} becomes the number {}'.format(string, integer)
self.label.setText(text)
if __name__ == '__main__':
app = qtw.QApplication()
main_window = MainWindow()
sys.exit(app.exec_())