Friday, December 30, 2011

Access QML Element properties from C++

Qt provides various method for working with QML. This following tutorial shows, how a QML Element properties can be accessed and modified from C++ code using QDeclarativeProperty class.

It will show a simple idea on accessing properties which cannot be accessed directly.

main.qml

import QtQuick 1.1

Rectangle {
    id: parentRect
    property bool layoutValue : LayoutMirroring.enabled ? true : false;// Read Only
    LayoutMirroring.enabled: false
    LayoutMirroring.childrenInherit: true
    width: 300; height: 50
    color: "yellow"
    border.width: 1

    Row {
        anchors { left: parent.left; margins: 5 }
        y: 5; spacing: 5

        Repeater {
            model: 5

            Rectangle {
                color: "red"
                opacity: (5 - index) / 5
                width: 40; height: 40

                Text {
                    text: index + 1
                    anchors.centerIn: parent
                }
            }
        }
    }
}


main.cpp

#include 
#include 
#include 
#include 
#include "qmlapplicationviewer.h"

Q_DECL_EXPORT int main(int argc, char *argv[])
{
    QScopedPointer app(createApplication(argc, argv));
    QScopedPointer viewer(QmlApplicationViewer::create());

    viewer->setOrientation(QmlApplicationViewer::ScreenOrientationAuto);
    viewer->setMainQmlFile(QLatin1String("qml/Test/main.qml"));
    QDeclarativeProperty propLayout(viewer->rootObject(),"layoutValue");
    QDeclarativeProperty propLayoutMargin(viewer->rootObject(),"anchors.leftMargin");

    qDebug() << "Layout Property :" << propLayout.read().toBool();
    qDebug() << "Layout Margin :" << propLayoutMargin.read().toReal();

    qDebug() << "Property Modified? " << propLayoutMargin.write(QVariant::fromValue(20));
    if(propLayout.type() == QDeclarativeProperty::Invalid)
        qDebug() << "Invalid Layout Mirror property";
    if(propLayoutMargin.type() == QDeclarativeProperty::Invalid)
        qDebug() << "Invalid Anchor Margin property";
    viewer->showExpanded();

    return app->exec();
} 
Your Ad Here