keskiviikko 30. tammikuuta 2013

Searching and manipulating Items in a QML-file through C++/Qt logic

Say you would like to manipulate an Item you have declared in a QML-file through C++/Qt logic. This example is again based on the Qt Quick 2 Application template provided by Qt Creator 2.61, and run on Qt 5.0. We add a new Item (these are called QQuickItems in logic) to the main.qml file with the id "manipulatedItem", so that it looks something like this:

import QtQuick 2.0

Rectangle {
    width: 360
    height: 360
    Text {
        text: qsTr("Hello World")
        anchors.centerIn: parent
    }
    MouseArea {
        anchors.fill: parent
        onClicked: {
            Qt.quit();
        }
    }
    Rectangle {
        id: notObjectName
        objectName: "manipulateMe"
        color: "blue"
        anchors.fill: parent
    }
}

Notice that we define the property "objectName" for this new Item. Now we can modify the added QML-item in main.cpp:

#include <QtGui/QGuiApplication>
#include "qtquick2applicationviewer.h"
#include <QQuickItem>                     // Notice this include

int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);

    QtQuick2ApplicationViewer viewer;
    viewer.setMainQmlFile(QStringLiteral("qml/untitled1/main.qml"));

    // The findChild-method is used to locate the child object called "manipulateMe".
    // This searching is done recursively, so the whole "branch" is searched. Notice
    // that this searched name is NOT the id of the QML-item, but it is the property
    // called "objectName".
    QQuickItem * manipulatedQQuickItem = viewer.rootObject()->
            findChild<QQuickItem*>("manipulateMe");

    // Now we can manipulate the object through this pointer.
    // But what if the pointer becomes invalid?
    if (manipulatedQQuickItem)
    {
        manipulatedQQuickItem->setOpacity(0.5);
        manipulatedQQuickItem->setProperty("color","red");
    }
    viewer.showExpanded();
    return app.exec();
}

Now you can now modify the Item anyway you like. But there is a risk that the Item gets destroyed before you modify it. So as always you have to be careful with dangling pointers.

Ei kommentteja:

Lähetä kommentti