QPushButton onClick without explicit connect-call



  • Hi,

    I am working on an existing QT application und I try to understand something:

    The application has a QPushButton and when it is clicked, a function called void MainWindow::on_sendCommandPushButton_clicked() is called. What I don't understand is that there is NO connect(...) call anywhere in the code. I thought I would have to connect the click-signal to the function for it to work.

    My current guess is that there is an implicit connect somewhere, the buttons name is sendCommandPushButton and if there is a function on_<name>_clicked it will get called without an explicit connect-call. Is this correct?

    Unfortunately I did not find anything browsing the documentation.

    And I can rename the function (both declaration and implementation) and it still compiles and the renamed function is not called when the button is clicked. If there were a connect-call I missed in the code, I would expect to get a compile error.

    Can anyone shed light on this issue?

    Cheers,
    Torsten



  • @Torsten-S. IIRC this is handled by the code generated by the form compiler. It uses QMetaObject to introspect the objects involved and binds signals to slots in exactly the way you describe. That is "on_" + ui_object_name + "_" + signal_name is bound for you.

    Just to clarify. The QPushButton is in a UI form right? That is in you MainWindow ctor your have something like "ui->setupUi(this);".



  • Hi Matthew,

    @matthew.kuiash said in QPushButton onClick without explicit connect-call:

    @Torsten-S. IIRC this is handled by the UI loader. I can introspect the object doing the loading and binds signals to slots in exactly the way you describe. That is "on_" + ui_object_name + "_" + signal_name is bound for you.

    Just to clarify. The QPushButton is in a UI form right? That is in you MainWindow ctor your have something like "ui->setupUi(this);".

    Yes, that is correct. The QPushButton is in a UI form and there is a ui->setupUi(this) in the MainWindw-class.

    So this is expected behaviour?! It is just that I have not found any documentation on this. Everything I read emphasizes to use connect(...) to connect to the signals.

    Thanks,
    Torsten



  • @Torsten-S. OK, I think the magic function is this one http://doc.qt.io/qt-5/qmetaobject.html#connectSlotsByName

    Very cool. Look in the ui_MainWindow.h generated by the form compiler and you'll find that lots of UI objects are created and parented to MainWindow then the above function binds everything for you.



  • Great. Thanks for the quick clarification. I am going to read more about this. One less point of confusion :)

    Cheers,
    Torsten



  • @Torsten-S. No problem. Have a nice day!


Log in to reply
 

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