Quesitons on QObjectList
-
I am trying to understand QObjectList, and found the following description from Qt documentation:
const QObjectList & QObject::children() const
What does this mean? Why is there a & and two const, with one at the end? How can I use it to return the children objects? Can you provide an example? Thanks.
-
@pdsc_dy
the&
get thereference
of the return value, just avoid copying
the firstconst
avoid thereference
being modified
the secondconst
says there is no member of the class will be modified in the methodthese are the c++ syntax, so read some c++ tutorial or reference for more information, ex. c++ reference
and the
QObjectList
is an alias ofQList<QObject*>
, so read QList document for more information about how to use itas for an example, I create a widget that has three labels, and I show the widget's children type in the third label
#include <QApplication> #include <QtWidgets> int main( int argc , char *argv[] ) { QApplication app( argc , argv ); QWidget window; QLabel *label1 = new QLabel( "Label1" ); QLabel *label2 = new QLabel( "Label2" ); QLabel *label3 = new QLabel( "Children Type: " ); QVBoxLayout *layout = new QVBoxLayout; layout->addWidget( label1 ); layout->addWidget( label2 ); layout->addWidget( label3 ); window.setLayout( layout ); for( QObject *child : window.children() ) label3->setText( label3->text() + child->metaObject()->className() + " " ); window.show(); return app.exec(); }
this is the output
demo