2

I'm wondering what's the difference between a child object or an object as a property:

Rectangle {
    Button {
        id: myButton

    }
}

and

Rectangle{
    property Button myButton: Button {

    }
}

I know that you can access the button in the first example (via id) from more places in the QML code (see this thread). Are there performance differences or other differences?

The qt.io wiki doesn't help me on this.

Community
  • 1
  • 1
David
  • 35
  • 1
  • 4
  • There's plenty of documentation on this subject, which can be found using the terms you used in your question. For example: http://doc.qt.io/qt-5/qtqml-syntax-objectattributes.html#property-attributes and http://doc.qt.io/qt-5/qtqml-syntax-basics.html#child-objects – Mitch May 20 '15 at 08:30
  • You may want to look at http://doc.qt.io/qt-5/qtquick-visualcanvas-visualparent.html which explains what's fundamentally different between the two examples. – peppe May 21 '15 at 09:10
  • Thank you, I read it but didn't get it before. Now, with the help of the two answers, it's clear to me. – David May 21 '15 at 11:30

2 Answers2

0

Well, in the second scenario the button will not be visible. It will exist as a property, but since it is not a child in the object tree it will not be displayed. So it is pretty much useless to have a visual element as a property.

There is no parent/child relation between an object and its properties. It exists only for QObject and derived trees, which are a fundamental concept to structuring Qt applications. Also, this implies that you can't have something like an int as a child, it can only be a property. Properties imply data, not structure.

As cmannett85 noted, children will also be interfaced as a list property depending on their type, but in QML you should rarely be concerned with that, if ever... But while children are interfaced as properties, properties do not get the complimentary treatment.

Note that you can have it both ways.

Rectangle{
    property alias myButton: button

    Button {
        id: button
    }        
}

This way the button will be visible, and you will still have a reference to it as a property if you want to access it from outside the current QML file, which does not work with ids - they are valid only for the QML file they are in. Dynamic scoping works for properties, but not for ids.

GrecKo
  • 6,615
  • 19
  • 23
dtech
  • 47,916
  • 17
  • 112
  • 190
0

Both objects are attached to properties. All aggregate objects in an Item are attached to the default data property, from there they're copied into the children or resources properties depending on their type.

Also note that Item derived objects are only visible when part of the visual object tree which forms the scenegraph, and the entire scenegraph can only have one root. So you can't just assign an Item derived object to any property and expect it to be visible without extra work.

cmannett85
  • 21,725
  • 8
  • 76
  • 119