PDA

View Full Version : Best way to access one element (widget or layout)



Julieng031
30th September 2013, 16:45
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:



class X {

private:
QLineEdit * toto;
QLineEdit * toto2;
QLineEdit * toto3;
....
}


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.

wysota
30th September 2013, 20:54
The best way is through private members (e.g. pointers) and proper encapsulation.

Julieng031
30th September 2013, 23:00
Ok, thanks for your answer! I'm going to continue with this way to implement my code.

ChrisW67
1st October 2013, 00:11
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).

Julieng031
1st October 2013, 07:35
Thanks a lot, ChrisW67, for you additional answer.