PySide : How to get the clicked QPushButton object in the QPushButton clicked slot?

陌路散爱 提交于 2019-12-03 15:48:52
qurban

Here is what I did to solve the problem:

button = QtGui.QPushButton("start go")
button.clicked.connect(lambda: self.buttonClick(button))

def buttonClick(self, button):
    print button.text()

You can just use self.sender() to determine the object that initiated the signal.

In your code something along the lines of this should work.

button = QtGui.QPushButton("start go")
button.clicked.connect(self.buttonClick)

def buttonClick(self):
    print self.sender().text()

Usually, most widgets will be created in the setup code for the main window. It is a good idea to always add these widget as attributes of the main window so that they can be accessed easily later on:

class MainWindow(QtGui.QMainWindow):
    def __init__(self, parent=None)
        super(MainWindow, self).__init__(parent)
        ...
        self.button = QtGui.QPushButton("start go")
        self.button.clicked.connect(self.buttonClick)
        ...

    def buttonClick(self):
        print(self.button.text())

If you have lots of buttons that all use the same handler, you could add the buttons to a QButtonGroup, and connect the handler to its buttonClicked signal. This signal can send either the clicked button, or an identifier that you specify yourself.

There is also the possibility of using self.sender() to get a reference to the object that sent the signal. However, this is sometimes considered to be bad practice, because it undermines the main reason for using signals in the first place (see the warnings in the docs for sender for more on this).

I actually wanted to comment on a comment in answer #1 but don't have enough reputation to do so yet :). The comment is "Can be tricky to use lambda like this when connecting lots of buttons in a loop, though." And that's exactly what I needed to do when I found this page.

Doing this in a loop doesn't work:

for button in button_list :
    button.clicked().connect( lambda: self.buttonClick( button )

Your callback will always get called with the last button in button_list (for why see information on this page I also just found - https://blog.mister-muffin.de/2011/08/14/python-for-loop-scope-and-nested-functions)

Do this instead, it works:

for button in button_list :
    button.clicked().connect( lambda b=button: self.buttonClick( b ))
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!