[SOLVED] Signals and Slots for dynamically created instances of classes
-
Hello,
I have two classes that I create instances of during run time. I am trying to connect a signal and a slot of the two instances, however I am not sure how to do this because upon initialization the instances point to nothing and only get created somewhere in the middle of my application running. I'm not sure how to connect the two signals and slots unless they are created before I call the connect() function.
I don;t know if it matters, but this is the line I use:
@connect(directory_Widget, SIGNAL(editProgramSignal()), editProgram_Widget, SLOT(editProgramSlot()));@
The problem is that directoty_Widget and editProgram_Widget (which are pointer) are NULL at initialization and only get point to memory after a equence of things happen from the user upon run time. Any ideas on how to connect the signals and slots in this fashion??
Thanks!
-
If the instances of the objects are not existing you cannot connect them. You need to create the instances of the instances before connecting.
See this example from the "documentation of signals and slots":http://qt-project.org/doc/qt-4.8/signalsandslots.html
@
Counter a, b;
QObject::connect(&a, SIGNAL(valueChanged(int)),
&b, SLOT(setValue(int)));a.setValue(12); // a.value() == 12, b.value() == 12 b.setValue(48); // a.value() == 12, b.value() == 48
@
There you see that you have to connect the 'addresses' it is not important this is a pointer.
-
I can not understand why not call connect just after both your directory_Widget and editProgram_Widget have been created.
-
Because I did not allocate an address space for the widgets until runtime. I guess there is no way around this and I should allocate them upon compiling. I just had a lot and wanted to do this through a simple function upon runtime. I just used the brute force method and got it to work though.
-
Wondering what you are considering as brute force.
It is the typical practice to allocate memory for class instance. Afterwards ensure that the signals send by your widget are received somewhere. The same is with receiver of signals. You ensure that you are receiving the signals you required from somewhere.Have a closer look to the example I have provided above. It is from the signal and slot documentation and it explains in short what is happening.
Since the signal is sent from "a" to "b" and not the reverse, only values set in "a" will be automatically copied to "b". See also that this is the same class definition.
You can connect 10 or 100 instances (e.g. b00 up to b99) to "a". As soon as you assign a value to "a" it will be automatically copied to "b"s. However, the assignment to any of "b"s will not affect the contents of the others.
You have to provide the addresses of the instances for connecting. If the address happens to be in a pointer that is fine. The address is copied from the pointer. Not the address of the pointer.