是否有人知道如何从C ++访问和存储动态创建的QML对象? 我在Qt网站上使用了以下代码来创建动态QML对象并尝试将它们存储在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)
}
}
谢谢。
CV
答案 0 :(得分: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()可能会工作,也可能不会。你必须尝试。