从C++访问动态QML对象

3

有没有人知道如何从C++中访问和存储动态创建的QML对象?

我使用了Qt网站上建议的以下代码来创建动态QML对象,并尝试将它们存储在QML列表类型中。

    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)
        }
     }

谢谢。
简历
1个回答

2

关于此事有相关文档。 http://doc.qt.nokia.com/4.7/qml-list.html

要实现这个,你需要将数组作为列表来实现。

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)
    }

来自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();

未经测试的代码。 嗯,我不确定这个。但也许QVariant.toList()会起作用,也可能不会。你需要尝试一下。


抱歉,我应该提到,我正在寻找在C++中访问这些对象的方法。如何从C++应用程序访问“myArray”? - Chenna V

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接