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

ありがとうございました。

履歴書

4

1 に答える 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() が機能するか、機能しない可能性があります。試してみる必要があります。

于 2011-05-24T01:33:12.180 に答える