PDA

View Full Version : Acessing other objects "higher up"



CryoGenFX
16th October 2007, 01:13
Ok, first off, sorry for what may be a moronic question, but it _is_ the newbie section after all :)

I'm learning c++/Qt4 by trial and error, and some reading, and one thing I consistently find myself needing as my application grows, is the need to alter data in other instances of my classes "higher up the chain". Confused? Me too, so an example is in order.

I have a MyClass, and in that implementation, I create a SubClass object, and in the SubClass implementation, I create YetAnotherSubClass. Now, in the YetAnotherSubClass implementation, I do some calculations, and have the need to write that value into a QLabel in the "upper" MyClass object. now, in the beginning, I found that object manually each time with a zillion parent()->parent calls (horrible, I know), but now I've found a slightly better way of doing that, and it's kinda like this (off memory here, so bear with me)

a loop from qApp that finds my MainApplication object, then loop through it's children looking for the object I want, say findChild<MyClass *>() and then call the function that sets that value.

But somehow I can't shake the feeling that this is wrong and cumbersome (not to mention it takes up about 10 lines of code each time I need to do it), and it's not the way "real programmers" do things. What have I missed here? I suspect it might be signal/slot related, but I can't connect the signal to the slot unless i find that top object first, so any ideas you care to toss in my general direction would be most appreciated :)

Regards, a hungry and growing Qt4 enthusiast.

marcel
16th October 2007, 06:53
What about a signal chain? Connect a signal from the inner most class to a signal in the middle class and then connect the middle class signal to a slot in the outer class.

CryoGenFX
17th October 2007, 00:01
hm, can you create custom signals? I can't find anything about it in the docs, other than that they are generated by the moc and must never be implemented in the cpp file...

and how would that make the sender() return value, wouldn't it just return the latest "relay". In some slots I use sender() and objectName() as a means of getting data across.

:confused: hm, not easy this bit :) Also, I have probably about 30 or 40 places in the code where this is needed as it stands now, so it'd be a fair bit of signalling then :)

marcel
17th October 2007, 06:35
Of course you can create custom signals...
F.e:


class SomeClass
{
Q_OBJECT

...
signals:
void mySignal();
...
}


You can pass data between signals and slots via their parameters.

CryoGenFX
17th October 2007, 19:55
Oh my...
this just rocked my world. I've rewritten a few of my usecases to this signal chain thingy you speak of, and wow, have I been doing the wrong thing all along.

thanks a bunch man, this changes everything.