[Qt-qml] Recommended way to parametrize QML items?

Tomas Junnonen tomas.junnonen at nokia.com
Wed Nov 17 17:05:52 CET 2010


On 11/17/2010 04:40 PM, Kellomaki Pertti (Nokia-MS/Tampere) wrote:
> On 11/17/2010 03:59 PM, Junnonen Tomas (Nokia-MS/Helsinki) wrote:
>> The parametrized bar item doesn't have to be a direct child of Foo
>> either. Another way is to use the onBarChanged signal to Do What You
>> Want(tm), for example if you need to anchor the item.
>>
> Thanks, that clarified things. How do I access bar's anchors within the
> signal handler though? I tried various permutations but did not quite
> figure it out yet.

"bar.anchors.top = top" for instance should just work.

> Could you modify the example so that Foo has a single Text element
> saying "This is bar", positioned just below whatever bar happens to be?

Simple but naive way:

Foo.qml:
import QtQuick 1.0

Rectangle {
     property Item bar

     Text {
         id: label
         text: "This is bar"
     }

     onBarChanged: {
         children = [bar, label]
         label.anchors.top = bar.bottom
     }
}

Because QML doesn't support in-place list manipulations, this isn't a 
very good solution as it restricts you from directly adding items to Foo 
by essentially hardcoding Foo's children.

A better way might be to use a placeholder item, a bit like in the 
original SpinBox implementation you mentioned:

Foo.qml:
import QtQuick 1.0

Rectangle {
     property Item bar

     Item {
         id: barPlaceHolder
         height: children[0] ? children[0].height : 0
         width: children[0] ? children[0].width : 0
     }

     Text {
         id: label
         text: "This is bar"
         anchors.top: barPlaceHolder.bottom
     }

     onBarChanged: {
         bar.parent = barPlaceHolder
     }
}

Regards,
Tomas



More information about the Qt-qml mailing list