Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Why does a functor slot must have exactly the same number of arguments as signal?



  • Hi,
    https://doc.qt.io/qt-5/qobject.html#connect-4 says;

    A function can be connected to a given signal if the signal has at least as many argument as the slot. A functor can be connected to a signal if they have exactly the same number of arguments.

    I'd like to know why. Is it just by design or a implementation issue? Any technical details?
    Thanks in advance.


  • Moderators

    @jsulm apparently an error in the documentation

    void functor(){
        qDebug() << Q_FUNC_INFO;
    }
    
    class Widget : public QWidget
    {
        Q_OBJECT
        QWidget *center2;
    public:
        explicit Widget(QWidget *parent = nullptr)
            : QWidget(parent), center2(new QWidget(this))
        {
            connect(this, &Widget::signalWithArgument, functor);
            auto t = new QTimer(this);
            connect(t, &QTimer::timeout, this,[=]()->void{emit signalWithArgument(1);});
            t->start(1000);
        }
    
    signals:
        void signalWithArgument(int);
    };
    
    
    
    int main(int argc, char *argv[])
    {
        QApplication a(argc, argv);
    
        Widget w;
        w.show();
    
        return a.exec();
    }
    
    #include "main.moc"
    

    works perfectly fine


  • Moderators

    @Xeonacid
    A problem of the c++ language, really

    You can't call a function that expects arguments, without arguments


  • Lifetime Qt Champion

    @J-Hilk But you can connect a signal which has more parameters than the slot.
    Apparently same does not work with functors.


  • Moderators

    @jsulm apparently an error in the documentation

    void functor(){
        qDebug() << Q_FUNC_INFO;
    }
    
    class Widget : public QWidget
    {
        Q_OBJECT
        QWidget *center2;
    public:
        explicit Widget(QWidget *parent = nullptr)
            : QWidget(parent), center2(new QWidget(this))
        {
            connect(this, &Widget::signalWithArgument, functor);
            auto t = new QTimer(this);
            connect(t, &QTimer::timeout, this,[=]()->void{emit signalWithArgument(1);});
            t->start(1000);
        }
    
    signals:
        void signalWithArgument(int);
    };
    
    
    
    int main(int argc, char *argv[])
    {
        QApplication a(argc, argv);
    
        Widget w;
        w.show();
    
        return a.exec();
    }
    
    #include "main.moc"
    

    works perfectly fine



  • @J-Hilk Thanks! Hope it can be fixed soon.
    @jsulm Same thanks!