PyQt5最全87 信号与槽之使用partial对象为槽函数传递参数
from PyQt5.QtWidgets import *
from functools import partial
import sys
class PartialSlotArg(QMainWindow):
"""
使用partial对象为槽函数传递参数
"""
def __init__(self):
super(PartialSlotArg, self).__init__()
self.setWindowTitle('使用partial对象为槽函数传递参数')
self.resize(400, 300)
button1 = QPushButton('按钮1')
button2 = QPushButton('按钮2')
# 创造partial类的实例
x = 20
button1.clicked.connect(partial(self.onButtonClick, 10, x))
button2.clicked.connect(partial(self.onButtonClick, x, -20))
layout = QHBoxLayout()
layout.addWidget(button1)
layout.addWidget(button2)
mainFrame = QWidget()
mainFrame.setLayout(layout) # 这个地方终于明白了吧,setlayout是对于窗口的
self.setCentralWidget(mainFrame)
def onButtonClick(self, m, n):
print('m + n = ', m + n)
QMessageBox.information(self, '结果', str(m + n))
if __name__ == '__main__':
app = QApplication(sys.argv)
example = PartialSlotArg()
print(example.__doc__)
example.show()
sys.exit(app.exec_())
结果
点击按钮1
点击按钮2
使用partial对象为槽函数传递参数
m + n = 30
m + n = 0
第二种方法:partial对象!!!