Best way to access one element (widget or layout)
Hello,
I would llike to have an advice about the way to access elements in QT.
Most of the tutorials I've seen show classes with private pointers to access the elements like this:
Code:
class X {
private:
....
}
If the GUI is complex, there is quickly a long list of variables.
I have also found "findChild" functions.
What is the best way to manipulate elements ? Are there differences in terms of memory occupation, access time... ?
Thanks in advance.
Re: Best way to access one element (widget or layout)
The best way is through private members (e.g. pointers) and proper encapsulation.
Re: Best way to access one element (widget or layout)
Ok, thanks for your answer! I'm going to continue with this way to implement my code.
Re: Best way to access one element (widget or layout)
There's a small overhead of a pointer-per-widget, but member variables are the way to do it for the vast majority of cases. If you use Designer and uic then the generated code uses member variables in exactly the fashion you describe.
The alternative is to not keep those pointers, but uniquely name each widget, and then use QObject::findChild() to walk recursively down the QObject ownership tree looking for a match (or matches) on name and type. A whole tree walk comparing and casting is much slower then direct access via a stored pointer. This approach is useful for dynamically constructed UIs where the structure cannot be known in advance (perhaps using QUiLoader).
Re: Best way to access one element (widget or layout)
Thanks a lot, ChrisW67, for you additional answer.