[Interest] Finding the root QQuickItem in a QQml(Application)Engine

Sze Howe Koh szehowe.koh at gmail.com
Tue May 12 01:48:40 CEST 2015


On 11 May 2015 at 23:47, Ben Lau <xbenlau at gmail.com> wrote:
>
> On 11 May 2015 at 21:06, Sze Howe Koh <szehowe.koh at gmail.com> wrote:
>>
>> Hello,
>>
>> Is there an analogue of QQuickView::rootItem() for QQml(Application)Engine?
>>
>> The shortest way I could think of involves jumping through a few hoops, e.g.:
>>
>>     QQmlApplicationEngine engine;
>>     // ...
>>     auto window = engine.rootObjects().first();
>>     auto aQuickItem = qobject_cast<QQuickItem*>(window->children().first());
>>     auto rootItem = aQuickItem->parentItem();
>>
>>
>> Regards,
>> Sze-Howe
>
> Hi,
>
> I use this piece of code to find the root QQuickItem (part of my test suite):
>
>     engine.load(url);
>
>     QObject *rootObject = engine.rootObjects().first();
>
>
>     QQuickWindow *window = qobject_cast<QQuickWindow*>(rootObject);
>
>     if (window) {
>
>         setTestableRootObject(window->children().first());


Thank you for your suggestions, Ben and Gunnar!

To clarify, I was after the invisible root item that a QQuickWindow
creates. Currently, this is implemented (privately) as a
QQuickRootItem:
http://code.woboq.org/qt5/qtdeclarative/src/quick/items/qquickwindow_p.h.html#QQuickRootItem

If the top-level item is a Window/ApplicationWindow which has
contents, then engine.rootObjects().first()->children().first()
returns the first QQuickItem inside the Window/ApplicationWindow.
However, this is actually not the "root" item. You can find the true
root by calling

    qDebug() <<
qobject_cast<QQuickItem*>(engine.rootObjects().first()->children().first())->parentItem()


My use-case is to dynamically add items from C++, as siblings of the
existing QQuickItems.


>     } else {
>
>         setTestableRootObject(rootObject);
>
>     }

Is this case valid? IIRC, QQmlApplicationEngine requires a
Window/ApplicationWindow at the top-level in order to display
anything.


Regards,
Sze-Howe



More information about the Interest mailing list