3

Is anyone aware of how to access and store dynamically created QML objects from C++? I used the following code suggested on Qt Site for creating dynamic QML objects and trying to store them in a QML list type

    property list<Button> listButtons: [
        Button{ }
    ]
    function addButton(buttonname) {
        console.log("Creating Pin: "+buttonname)
        var component = Qt.createComponent("Button.qml");
        if (component.status == Component.Ready)
        {
            var newbutton = component.createObject(node);
            newbutton.x = 20;
            newbutton.y = 30;
            listButtons.append(newbutton) //I get a error here: listButtons.append [undefined] is not a function
        }
        else
        {
            console.log("Unable to create button: "+buttonname)
        }
     }

Thank you.

CV

1 Answer 1

2

There is documentation regarding this. http://doc.qt.nokia.com/4.7/qml-list.html

To achieve this you need to implement an array as a list

import QtQuick 1.0
import "script.js" as JsScript

Rectangle {
    width: 360
    height: 360

    function getList(){
        return JsScript.array;
    }

    Text {
        anchors.centerIn: parent
        text: "Hello World"
    }
    Item {
     Component.onCompleted: {
         console.log('complemented');
         JsScript.addItem('abc')
         console.log("Added:", JsScript.array[0])
     }
    }
}

script.js

var array = new Array();

function  getArray(){
    return array;
}
    function addItem(item) {
     array.push(item)
    }

from c++

QDeclarativeEngine engine;
QDeclarativeComponent component(&engine, "MyItem.qml");
QObject *object = component.create();

QVariant returnedValue;
QVariant msg = "Hello from C++";
QMetaObject::invokeMethod(object, "myQmlFunction",
     Q_RETURN_ARG(QVariant, returnedValue),
     Q_ARG(QVariant, msg));

returnedValue.toList();

Untested code. hmmm, i am not sure about this.But maybe QVariant.toList() will work or maybe it wont.You'll have to try.

Sign up to request clarification or add additional context in comments.

1 Comment

Sry, I shud've mentioned, I was looking for accessing these objects in C++. How can I access "myArray" from a C++ application?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.