PyQt immediately calling function handler upon setup. Why?
-
Hi, I'm setting up a Python GUI using Qt5, QtCreator, pyuic, and some other stuff. My main app class inherits from QMainWindow and my UI. My initialization method calls a method that connects a button to a function handler with the following call:
self.button1.clicked.connect(fct_handler(params))
However, as per normal app operations, when the button is clicked without proper setup, it throws an error. My two questions are why is this button being clicked upon a call to the connect() method? And how can I catch this error to resume normal operations?
-
Hi and welcome to devnet,
Unless I'm mistaken your connect statement is wrong. Technically you are calling fct_handler inside that statement which is wrong. You should only pass the function name to connect.
Hope it helps
-
I want to call that function with parameters, though. Does that mean that I need to write a function handler specifically for calling my function with parameters? I don't understand the difference if the function is just going to be called either way.
-
@errolflynn You should write
self.button1.clicked.connect(ft_handler)
- this will register the functionft_handler
as a slot for theclicked
signal. On http://doc.qt.io/qt-5/qabstractbutton.html you see that the signature of that signal isvoid clicked(bool checked)
. In other words, when the signal is activated, your handler is called asft_handler(checked)
wherechecked
is eitherTrue
orFalse
. Per the signature of theclicked
signal, this is the only information you will get out of the signal.If you want to pass additional parameters, you indeed will need to create a separate function that encodes those extra parameters and passes them to the handler. In Python it makes a lot of sense to use a lambda for it, for instance:
self.button1.clicked.connect(lambda checked: fct_handler(par1, par2, par3, checked))
Hope this helps