How to pass arguments to functions by the click of button in PyQt?

后端 未结 6 1494
时光说笑
时光说笑 2020-12-07 20:45

I want to pass the arguments to a function when I click the button. What should I add to this line button.connect(button, QtCore.SIGNAL(\'clicked()\'), calluser(name))

6条回答
  •  不思量自难忘°
    2020-12-07 21:29

    The code shown below illustrates a method of associating data with generated buttons. For example, you could change the statement self.keydata[b] = key to store a tuple of data into self.keydata[b] for use when processing a button event later.

    Note, in the following code, assets is a previously-defined dictionary containing titles for buttons. In the processButton(self) routine, self.sender() is equal to an entry in the class variable buttons[].

    class Tab5(QtGui.QWidget):
        buttons, keydata = {}, {}
        def __init__(self, fileInfo, parent=None):
            super(Tab5, self).__init__(parent)
            layout = QtGui.QVBoxLayout()
    
            for key in sorted(assets):
                b = self.buttons[key] = QtGui.QPushButton(assets[key], self)
                b.clicked.connect(self.processButton)
                layout.addWidget(b)
                print 'b[key]=',b, ' b-text=',assets[key]
                self.keydata[b] = key
    
            layout.addStretch(1)
            self.setLayout(layout)
    
        def processButton(self):
             print 'sender=',self.sender(), ' s-text=',self.sender().text(), ' data[.]=', self.keydata[self.sender()] 
             pass
    

    Output was like the following, where the first four lines printed during the for loop, and the last four printed when the four buttons were pressed in order.

    b[key]=   b-text= K1
    b[key]=   b-text= K2
    b[key]=   b-text= K3
    b[key]=   b-text= K4
    sender=   s-text= K1  data[.]= L1
    sender=   s-text= K2  data[.]= L2
    sender=   s-text= K3  data[.]= L3
    sender=   s-text= K4  data[.]= L4
    

提交回复
热议问题