In this application I want to connect each button to one method which simply display the text of the button pressed. Instead of writing three different methods for three different buttons, I thought I can pass the button itself as an argument to the method:
import sys
from PyQt5 import QtWidgets as qtw
class MyWindow(qtw.QWidget):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.initUI()
def initUI(self):
grid = qtw.QGridLayout()
self.setLayout(grid)
self.btn_1 = qtw.QPushButton('1')
self.btn_2 = qtw.QPushButton('2')
self.btn_3 = qtw.QPushButton('3')
self.btn_1.clicked.connect(self.print_to_console(self.btn_1))
self.btn_2.clicked.connect(self.print_to_console(self.btn_2))
self.btn_3.clicked.connect(self.print_to_console(self.btn_3))
grid.addWidget(self.btn_1)
grid.addWidget(self.btn_2)
grid.addWidget(self.btn_3)
self.show()
def print_to_console(self, obj):
obj = qtw.QPushButton()
print(obj.text())
def main():
app = qtw.QApplication(sys.argv)
ex = MyWindow()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
But I get here this error messsage:
Traceback (most recent call last):
File "c:\Users\fibi\Documents\PyQt5\nine buttons\NineButtons - Kopie.py", line 48, in <module> main()
File "c:\Users\fibi\Documents\PyQt5\nine buttons\NineButtons - Kopie.py", line 43, in main ex = MyWindow()
File "c:\Users\fibi\Documents\PyQt5\nine buttons\NineButtons - Kopie.py", line 10, in __init__self.initUI()
File "c:\Users\fibi\Documents\PyQt5\nine buttons\NineButtons - Kopie.py", line 22, in initUI
self.btn_1.clicked.connect(self.print_to_console(self.btn_1))
TypeError: argument 1 has unexpected type 'NoneType'
Does anybody know what I'm doing wrong? Thanks for helping.
CodePudding user response:
All methods by default return None
. You need to pass a callable object to the connect
, so that the method can be called when the button is pressed.
so make the following changes (remove the ()
after self.print_to_console
):
self.btn_1.clicked.connect(self.print_to_console)
self.btn_2.clicked.connect(self.print_to_console)
self.btn_3.clicked.connect(self.print_to_console)
You can get the widget that sent the signal using QObject.sender()
. So your print_to_console
could be
def print_to_console(self):
obj = self.sender()
print(obj.text())