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

Qt5 new signal/slot connection syntax



  • Hello,

    If I have a class B derived from class A, where class A declares signals and implements virtual slots, is there a way to connect the overriden slots of an instance of class B stored as a pointer on A with the new syntax QObject::connect ?

    Thank you by advance!


  • Lifetime Qt Champion

    @mistralegna I don't know for sure, but you can just try and see how it behaves?



  • It works out of the box...
    The example below will print "b"

    a.h

    #ifndef A_H
    #define A_H
    #include <QObject>
    #include <QDebug>
    class A : public QObject
    {
        Q_OBJECT
    public:
        explicit A(QObject *parent = nullptr) : QObject(parent){}
        virtual ~A() = default;
    public slots:
        virtual void test(){
            qDebug("a");
        }
    
    
    };
    #endif // A_H
    

    b.h

    #ifndef B_H
    #define B_H
    
    #include "a.h"
    
    class B : public A
    {
        Q_OBJECT
    public:
        explicit B(QObject *parent = nullptr) : A(parent){};
        virtual ~B() = default;
    public slots:
        virtual void test() override{
            qDebug("b");
        }
    };
    
    #endif // B_H
    

    main.cpp

    #include <QCoreApplication>
    #include "b.h"
    #include <QTimer>
    
    
    int main(int argc, char *argv[]) {
        QCoreApplication appl(argc,argv);
        A* testingB=new B();
        QTimer testTimer;
        testTimer.setSingleShot(true);
        QObject::connect(&testTimer,&QTimer::timeout,testingB,&A::test);
        testTimer.start(100);
        appl.exec();
        delete testingB;
        return 0;
    }
    
    


  • Thank you very much for your answer.

    Is it possible to use this syntax without having to include the headers where the signals/slots are defined ?

    Thank you by advance!



  • @mistralegna In my example you can #include "a.h" instead of #include "b.h" in main.cpp as long as testingB is created somewhere else


Log in to reply