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?


  • Lifetime Qt Champion

    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 function ft_handler as a slot for the clicked signal. On http://doc.qt.io/qt-5/qabstractbutton.html you see that the signature of that signal is void clicked(bool checked). In other words, when the signal is activated, your handler is called as ft_handler(checked) where checked is either True or False. Per the signature of the clicked 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



Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.