Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Qt signal-slot confusion

I am working on a project where I am having to create a Qt signal-slot connection from the constructor of a class to the class it's initialized inside. This is how the codes look like. I want both the connection mentioned below to work but from what the output suggests, only connection#1 works. My question is how to make connection#2 work!

class A

class classA :public QWidget{
    Q_OBJECT
public:
    classA(){
             emit this->demoSignalA();
            }
signals:
    void demoSignalA();
public slots:
    void demoSlotA(){qDebug()<<"SIGNAL FROM CLASS B"}
};

Class B

class classB :public QWidget{
    Q_OBJECT
public:
    classB(){
             classA *a = new classA;
             connect(this, SIGNAL(demoSignalB()), a, SLOT(demoSlotA()));  //WORKS
             connect(a, SIGNAL(demoSignalA()), this, SLOT(demoSlotB()));  //DOESN'T WORK
             emit this->demoSignalB();
            }
signals:
    void demoSignalB();
public slots:
    void demoSlotB(){qDebug()<<"SIGNAL FROM CLASS A";}
};

MAIN

int main(int argc, char *argv[]){
    QApplication a(argc, argv);
    ...
    ...
    classB b;                     //INVOCATION INITIATED

    return a.exec();

}

OUTPUT

SIGNAL FROM CLASS B
like image 233
Killswitch Avatar asked Dec 31 '25 01:12

Killswitch


1 Answers

If you follow the sequence of the code, it should be clear that at the point where you call

emit this->demoSignalA();

in the first line of the classB constructor, the connection has not yet been made. If the connection has not been made then the slot sill not be executed when you emit the signal.

You should emit both signals after the connections have been made, in the classB constructor.

(As a matter of principle it's probably better not to start emitting signals until you have finished the constructor, but that's not important here)

like image 72
DJClayworth Avatar answered Jan 01 '26 18:01

DJClayworth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!