Qt World Summit: Register Today!

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 the reference of the return value, just avoid copying
    the first const avoid the reference being modified
    the second const says there is no member of the class will be modified in the method

    these are the c++ syntax, so read some c++ tutorial or reference for more information, ex. c++ reference

    and the QObjectList is an alias of QList<QObject*>, so read QList document for more information about how to use it

    as 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() + " " );
      return app.exec();

    this is the output

  • what a fantastic explanation! This is very helpful.

Log in to reply