[Qt-qml] Find by id.

michael.brasser at nokia.com michael.brasser at nokia.com
Thu Nov 4 23:44:28 CET 2010


Hi,

On 04/11/2010, at 10:26 PM, ext René Hansen wrote:

> I'd like to be able to find child objects in a QML structure and to do
> that, I've exposed a new QML Object with qmlRegisterType, which provides
> me with:
> 
> QObject *QmlUnitTestHelper::getChildById(QObject *parent, QString name) {
>        return parent->findChild<QObject *>(name);
> }
> 
> And in Qml I have something like this:
> 
> Rectangle {
> 
>        QmlUnitTestHelper {
>                id: quth
>        }
> 
>        Rectangle {
>                id:outerRect
>                Rectangle {
>                id:innerRect
>                Text {
>                        id:label
>                        text: "Hello World"
>                }
>        }
>        }
> }
> 
> Which should enable me to test in something like this manner:
> 
> quth.getChildById(outerRect, "innerRect").label.text == "Hello World"
> 
> However, this doesn't work as expected, so I guess my assuming the QML
> id property being the same as a QObjects objectName is faulty.

That's correct -- id and objectName are separate. You can explicitly give a QML item an objectName, though, if needed:

Rectangle {
    id: myRect
    objectName: "theRectangle"
}

(Bea has just added some great documentation on this, which should hopefully be showing up on the website soon)

> How would I go about doing something like this?

For the above example, you should be able to test the label's text with:
label.text == "Hello World"
(within a component, the id space is "flat", rather than qualified)

If you need to access the item from outside the component, a property alias (http://doc.qt.nokia.com/4.7/qml-extending-types.html#property-aliases) might help. You could for example add

property alias testLabel: label

to the top-most Rectangle to make label accessible to the "outside world" via testLabel.

>From the class name, it looks like you might be looking at writing autotests in QML? If so (and If you haven't seen them already), here are a few projects that might be of interest:
* qmlunit (https://github.com/fgrehm/qmlunit)
* the Qt3D team's QML unit testing (http://qt.gitorious.org/qt-labs/qt3d/trees/master/tests/auto/qml3d)

Regards,
Michael



More information about the Qt-qml mailing list