Qt 在QML中动态创建按钮

Qt 在QML中动态创建按钮,qt,components,qml,qtquickcontrols,Qt,Components,Qml,Qtquickcontrols,在qt 5.2中,我尝试动态添加一个简单的按钮,如下所示: ApplicationWindow { id: appWindow width: 640 height: 420 minimumHeight: 400 minimumWidth: 600 function addButton() { var obj = Qt.createComponent("Button.qml"); if (obj.status

在qt 5.2中,我尝试动态添加一个简单的按钮,如下所示:

ApplicationWindow
{
    id: appWindow

    width: 640
    height: 420
    minimumHeight: 400
    minimumWidth: 600

    function addButton() {

        var obj = Qt.createComponent("Button.qml");

        if (obj.status == obj.Ready)
        {
            var button = obj.createObject(appWindow);
            button.color = "red";
            button.width=50;
            button.height=80;
            button.x=50; button.y=50;
           }
     }


    Button {
        anchors.centerIn: parent;
        text: "ok";

        onClicked: {
            addButton();
        }
    } ...
但在createComponent之后,我总是得到:

QQmlComponent:组件未就绪


出了什么问题?

为了确保组件准备就绪,最好的方法是在QML部件内、组件对象内声明它,以便它与文件的其余部分同时预加载:

ApplicationWindow {
    id: appWindow;

    Component {
        id: myButton;

        Button { }
    }

    function addButton () {
        var button = myButton.createObject (appWindow, {
                                                "color"  : "red",
                                                "width"  : 50,
                                                "height" : 80,
                                                "x"      : 50, 
                                                "y"      : 50
                                            });
    }

    ...
}

正如您所看到的,我还冒昧地向您展示了直接使用良好属性一次性创建对象的语法,而不是以老式方式手动设置它们。代码更加简洁,性能可能更高。

如示例所示。必须检查
对象.status
是否与
组件.Ready
枚举相等(
=
)。您还可以打印类似以下的错误:
if(component.status==component.Error){//Error Handling console.log(“错误加载组件:,component.errorString());}
我希望,
addButton
函数不会在静态按钮组件中解决。因此,请尝试添加
appWindow.addButton()onClicked
事件处理程序中的code>。我已经在文件的开头添加了import语句,它可以正常工作,没有错误。我看到一个按钮