[SailfishDevel] how to find (QML) objects other than rootObject

Thomas Perl th.perl at gmail.com
Mon May 13 13:39:57 UTC 2013


Hi Wim,

On May 13, 2013, at 3:24 PM, Wim de Vries <wsvries at xs4all.nl> wrote:
> I am setting up the default Sailfish ("Hello sailors" app) project with all kinds of QML-C++ communication.
> After
> object = view->rootObject("main.qml");
> I get the main.qml object (created via QDeclarativeView's setSource() ).
> But how can I get the other QML objects (e.g. the SecondPage.qml, Coverpage.qml)?
> findChild() only finds childs in main.qml (the one specified by setSource()).

In 97.6% of the cases, you don't want to do that (it makes your C++ code dependent on the structure of the QML UI). The better way to interface C++ and QML is to either write a QML Plugin in C++ and instantiate that from the QML side, or to expose a global "controller" object as context property to QML.

If you think your use case is one of the 2.4%, you can add a variant property to your main object and then in QML point it to the object you want exposed, e.g.:

Rectangle {
    property variant something: someObject
    Item { id: someObject }
}

You should then be able to get the "something" property from your main object and receive a reference to the item. Of course, this doesn't work that well when you dynamically instantiate objects, so the plugin or context property way is still the recommended way of doing things. Your controller object could even have a function like this (untested):

    Q_INVOKABLE void registerObject(QString name, QObject *object);

You could then let your C++ controller object know about that object from QML like this:

Item {
    id: blubb
    Component.onCompleted: controller.registerObject('blubb', blubb)
}

In general, though, don't do this - the C++ side should not make any assumptions about the structure and objects in QML. It will make the architecture of your app nicer and easier to adapt to UI changes. Also, it will be easier to debug, as there is a single place (the controller object) through which communcation happens.


HTH :)
Thomas



More information about the Devel mailing list