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).
sender()
. Can be tricky to uselambda
like this when connecting lots of buttons in a loop, though. – Polemics