Yes, it is possible, use sender()
method inside your slot. For example:
sender = self.sender()
Sender variable contains widget which emitted signal. Good example you can also find here.
I suppose that you wrote your slot as simple function, not as QObject
's subclass method. sender()
is a method of QObject
, so you can use this approach only in class.
Your error for example:
def buttonClicked(self):
sender = self.sender()
sender.setText('2')
class Example(QMainWindow):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
btn1 = QtGui.QPushButton("Button 1", self)
btn1.move(30, 50)
btn2 = QtGui.QPushButton("Button 2", self)
btn2.move(150, 50)
btn1.clicked.connect( buttonClicked)
btn2.clicked.connect(buttonClicked)
self.statusBar()
self.setGeometry(300, 300, 290, 150)
self.setWindowTitle('Event sender')
self.show()
def main():
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
Correct approach:
class Example(QMainWindow):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
btn1 = QtWidgets.QPushButton("Button 1", self)
btn1.move(30, 50)
btn2 = QtWidgets.QPushButton("Button 2", self)
btn2.move(150, 50)
btn1.clicked.connect(self.buttonClicked)
btn2.clicked.connect(self.buttonClicked)
self.statusBar()
self.setGeometry(300, 300, 290, 150)
self.setWindowTitle('Event sender')
self.show()
def buttonClicked(self):# now it is method
sender = self.sender()
sender.setText('2')
def main():
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
if __name__ == '__main__':
main()