PySide: How to get a clicked QPushButton with a mouse click in the slot for QPushButton?

I am new to PySide. I want to get a QPushButton obj object (for example, use it to get text) in its slotted slot.

button = QtGui.QPushButton("start go") button.clicked.connect(self.buttonClick) def buttonClick(self): ... # How can I get the button object? # print button.text() how to get the text : 'start go' ? 

Thanks!

+6
source share
5 answers

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() 
+11
source

You can simply use self.sender() to determine the object that triggered the signal.

In your code, something like this should work.

 button = QtGui.QPushButton("start go") button.clicked.connect(self.buttonClick) def buttonClick(self): print self.sender().text() 
+10
source

Typically, most widgets are created in the installation code for the main window. It is a good idea to always add this widget as attributes of the main window so that you can easily access them later:

 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 many buttons that use the same handler, you can add buttons to the QButtonGroup and connect the handler to the buttonClicked signal. This signal can be sent either by a pressed button or by an identifier that you specified yourself.

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

+1
source

I really wanted to comment on the comment in answer No. 1, but so far I have not enough reputation to do this :). Comment: "It can be difficult to use a lambda, for example, when connecting multiple buttons in a loop." And this is exactly what I needed to do when I found this page.

Doing this in a loop does not work:

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

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

Do it instead, it works:

 for button in button_list : button.clicked().connect( lambda b=button: self.buttonClick( b )) 
0
source

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

gives the following error. This does not identify the buttons.

TypeError: Qt native signal not raised

0
source

Source: https://habr.com/ru/post/959137/


All Articles