Killswitch
Killswitch

Reputation: 346

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

Upvotes: 3

Views: 124

Answers (1)

DJClayworth
DJClayworth

Reputation: 26886

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)

Upvotes: 6

Related Questions