less than 1 minute read

I’ve been using Qt for several years now in a couple different projects. Only today did I learn about QMetaObject::connectSlotsByName.

As the documentation states, this function will recursively search the given object for signals matching the format of:

void on_<object name>_<signal name>(<signal parameters>);

If you’re using Qt Designer and MOC’ing, this fuction gets called automatically in your ui_<mainwindow>.h file inside of setupUi(). This means that you don’t have to manually connect the objects in your .ui files. I didn’t know this! You can simply do something like:

class MainWindow : public QMainWindow
{
    ...

private Q_SLOTS:
    void on_button1_triggered();

}

And that’s it! You don’t have to define the signals/slots in Designer, you don’t have to manually connect them (as I had been doing). Nothing! It just works!

I had never seen this mentioned in any tutorial or even code examples. I only stumbled upon it when looking at another project for something completely unrelated. But this is a great time saver!

Tags:

Categories:

Updated: