problemofficer
problemofficer

Reputation: 435

Can I access Qt signals/slots of objects out of scope?

Do the Qt signals/slots follow the scope of native C++?

Let's say I have the following classes: House, Kitchen, Cellar, Stove and Shelf.

class House   {Kitchen kitchen, Cellar cellar;};
class Kitchen {Stove stove;};
class Cellar  {Shelf shelf;};

Now I want to send a signal from the shelf in the cellar to the stove in the kitchen. Is the only way to do this by connecting a signal from the shelf to the cellar and a slot from kitchen to the stove and then in house connecting cellar and kitchen? Or is there a way to do this directly?

I have a class that needs to communicate with a user interface and I wonder if I need to "proxy" all the various signals/slots through intermediate classes. Or is this an indicator of bad design?

Upvotes: 4

Views: 1342

Answers (3)

smerlin
smerlin

Reputation: 6566

You cant use signals/slots on classes which are no QObjects, so no, your example wont work whatsoever.

You can circumvent the encapsulation if you initilaize the child objects with their parent object, so you can do dirty tricks like: connect(this->shelf, SIGNAL(signalHere()), kitchen->children()[0], SLOT(aStoveSlot())). however this will only work if the first child of Kitchen is really a Stove... so since this is a obvious dependency, you should make this visible by making stove public, or by adding a stove accessor method.

Upvotes: 1

Frank Osterfeld
Frank Osterfeld

Reputation: 25155

You can do the connection in any method of House, as there you can access both objects. The "connector" must be able to access both sender and receiver, at compile time, that's all there is to it.

Upvotes: 4

g19fanatic
g19fanatic

Reputation: 10931

You should be able to just link a signal from the Shelf instance to the Stove instance

in House,

connect(cellar->shelf,SIGNAL(signalHere()),kitchen->stove,SLOT(slotHere()));

just make sure that shelf and stove are public variables in Kitchen and Cellar and you'll be set

Upvotes: 4

Related Questions