Steve
Steve

Reputation: 4097

Connecting/Binding Two QML Properties in C++

I would like to programmatically set a binding from one QML object to another in C++ when one QML has been created programmatically.

I have a custom qml object Boxxy defined in Boxxy.qml:

import QtQuick 2.0

Rectangle {
    property double bScale: 1.0
    color:"red"
    height: 50
    width: 100*bScale
}

I then use it as follows:

import QtQuick 2.15
import QtQuick.Window 2.15

Window {
    property  var mainObj: main
    property double viewScale : 1.0

    width: 640; height: 480
    visible: true

    Rectangle{
        id:main
        anchors.fill:parent

        Boxxy{           
            y: 75; height: 50;
            bScale:viewScale
        }
    }
}

Because my actually code has extensive existing logic and controllers in c++, I want to create some elements programmatically and then connect them in manually. In this example, I want to set bScale property to the parent control's viewScale property.

I create a Boxxy in c++ with:

    QObject * root = engine.rootObjects()[0];
    QQmlComponent component(&engine, QUrl("qrc:/Boxxy.qml"));
    QQuickItem*  main = qvariant_cast<QQuickItem*>(root->property("mainObj"));
    auto * box = (QQuickItem*)component.create();
    box->setParent(main);
    box->setParentItem(main);    

but then the bScale is not connected to the viewScale. I hoped to do

QObject::connect(root, SIGNAL("viewScaleChanged()"), box, SLOT("bScale"));

How can I duplicate the binding of the two properties in c++?

Upvotes: 0

Views: 834

Answers (1)

Mohammad Rahimi
Mohammad Rahimi

Reputation: 1123

I'm sure that this solution works when your QML types are created in QML the usual way. Rewrite your Boxxy as follow:

Item {
    id: name
    property real bScale: 1.0
    Rectangle {
        color:"red"
        height: 50
        width: 100 * parent.bScale
    }
}

Also in your code when ever viewScale changes bScale will update itself. To be sure, make your code work in pure qml. Then try C++ back-end approach.

Or maybe just a simple Repeater is enough for you.

Upvotes: 1

Related Questions