首页 > 学院 > 开发设计 > 正文

pyqt信号和槽传递额外参数

2019-11-06 08:02:52
字体:
来源:转载
供稿:网友
原文地址

环境:

python2.7.8

pyqt 4.11.1

使用Pyqt编程过程中,经常会遇到给槽函数传递额外参数的情况。但是信号-槽机制只是指定信号如何连接到槽,信号定义的参数被传递给槽,而额外的参数(用户定义)不能直接传递。

而传递额外参数又是很有用处。你可能使用一个槽处理多个组件的信号,有时要传递额外的信息。

一种方法是使用lambda表达式。

[python] view plain copyPRint?在CODE上查看代码片from PyQt4.QtCore import *  from PyQt4.QtGui import *    class MyForm(QMainWindow):      def __init__(self, parent=None):          super(MyForm, self).__init__(parent)          button1 = QPushButton('Button 1')          button2 = QPushButton('Button 1')          button1.clicked.connect(lambda: self.on_button(1))          button2.clicked.connect(lambda: self.on_button(2))            layout = QHBoxLayout()          layout.addWidget(button1)          layout.addWidget(button2)            main_frame = QWidget()          main_frame.setLayout(layout)            self.setCentralWidget(main_frame)        def on_button(self, n):          print('Button {0} clicked'.format(n))    if __name__ == "__main__":      import sys      app = Qapplication(sys.argv)      form = MyForm()      form.show()      app.exec_()  
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表