PDA

View Full Version : Create a connection for the parent class



maratk1n
30th October 2017, 13:08
Hi all!
I have a class for the main window, class A and class B, which inherits from class A:


MainWindow::MainWindow(){
...
A a;
connect(&a, SIGNAL(remoteSignal(bool)), this, SLOT(updateStates(bool)));
a.start();
B b;
connect(&b, SIGNAL(remoteSignal(bool)), this, SLOT(updateStates(bool)));
}

A::A()
{

}
void A::start(){
emit remoteSignal(true)
}

B::B()
{
A::start();
}

If I call the start method from object b for the parent class, there will not be any connections configured. How can I customize them?
Thanks!

d_stranz
30th October 2017, 15:52
MainWindow::MainWindow(){
...
A a;
connect(&a, SIGNAL(remoteSignal(bool)), this, SLOT(updateStates(bool)));
a.start();
B b;
connect(&b, SIGNAL(remoteSignal(bool)), this, SLOT(updateStates(bool)));
}

This code really does nothing at all. The instances of A and B are created on the stack as temporary variables in the MainWindow constructor and will be destroyed as soon as the destructor exits. When the instances are destroyed, any signal / slot connections involving them will also be destroyed.

Event though the temporary class A emits a signal through its start() method, this signal will not be acted on until the MainWindow constructor exits and control returns to the event loop. Because A was destroyed at the end of the constructor, the signal will also be removed from the event queue since the object that emitted it no longer exists.

Lesiok
31st October 2017, 06:44
B class emits signal in constructor before any connects. Use QTimer::singleShot with timeout 0 to emit signal.

maratk1n
31st October 2017, 09:26
[CODE]
This code really does nothing at all.
I apologize. The code is very large, so I figuratively wrote it. Of course, pointers to these instances are created in the class declaration, so a and b live as long as the main window class is alive. Connections also work.
My question is different. Class B is inherited from class A
class B: public A so if you call a method
A::start() from an instance of class B, the main window slot will not be called. How can this be done?

d_stranz
31st October 2017, 17:06
You haven't shown enough code to indicate what might be wrong. I'd suggest that you reduce the problem to these three classes (MainWindow, A, and B) with a bare-bones implementation of the classes, signals, and slots and determine if that works or not. If it doesn't work, post the complete code for the test project and we can look at it. Also be sure you have inserted the Q_OBJECT macro into the definitions of both A and B classes.

And as Lesiok says, be sure you make all of your signal / slot connections -before- any signals are emitted.