Search code examples
c++qtfunction-pointersqt5signals-slots

Parameter of type Func2 in QObject::connect?


QObject::connect takes parameters as following:

connect(const QtPrivate::FunctionPointer<Func1>::Object *sender, Func1 signal,
        const QtPrivate::FunctionPointer<Func2>::Object *receiver, Func2 slot);

Now let's say I'm creating a method QPushButton *newPushButton(const QString &text, Func2 slot);, how do I use the Func2 as a parameter's type, do I have to include something?

Here's an example of how I'd like my newPushButton to look like:

QPushButton *MyWidget::newPushButton(const QString &text, Func2 slot)
{
    QPushButton *pushButton = new QPushButton(text);
    layout->addWidget(pushButton);
    QObject::connect(pushButton, &QPushButton::clicked,
                     this, slot);
    return pushButton;
}

And now I could call it like so:

MyWidget::MyWidget(QWidget *parent = 0) : QWidget(parent)
{
    layout = new QVBoxLayout;
    myButton1 = newPushButton("My Button One", &MyWidget::on_myButton1_clicked);
    myButton2 = newPushButton("My Button Two", &MyWidget::on_myButton2_clicked);
    setLayout(layout);
}

However, I can't seem to figure out how to pass &MyWidget::slot as a parameter to the newPushButton() method without using templates (how does connect() do it?).

layout and both myButtons are members of MyWidget.


Solution

  • However, I can't seem to figure out how to pass &MyWidget::slot as a parameter to the newPushButton() method without using templates (how does connect() do it?).

    I don't get it -- those connect() overloads use templates: http://code.woboq.org/qt5/qtbase/src/corelib/kernel/qobject.h.html#212

    Can't you just do the very same?

    template<typename Func2> 
    QPushButton *MyWidget::newPushButton(const QString &text, Func2 slot)
    {
        QPushButton *pushButton = new QPushButton(text);
        layout->addWidget(pushButton);
        QObject::connect(pushButton, &QPushButton::clicked,
                         this, slot);
        return pushButton;
    }