34.pyqt信号和槽传递额外参数

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

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

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

    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_()

猜你喜欢

转载自www.cnblogs.com/ubuntu1987/p/12212910.html
今日推荐