QtQuick动态创建组件

来源:互联网 发布:在数据库中存储的是 编辑:程序博客网 时间:2024/04/27 05:45

1.Qt.createComponent 创建组件对象 createObject指定父元素

**Ani.QmlAnimatedImage {    id: animation; source: "qrc:/T.gif"    width: 40    height: 40}
**Text.QmlText{    width: 40    height: 40    text: "Hello"    verticalAlignment: Text.AlignBottom}
**main.Qmlimport QtQuick 2.7import QtQuick.Controls 2.0import QtQuick.Layouts 1.0ApplicationWindow {    visible: true    width: 640    height: 480    title: qsTr("Hello World")    property var ff: 0    SwipeView {        id: swipeView        anchors.fill: parent        currentIndex: tabBar.currentIndex        Page{            Flow{                id:grid                 spacing: 0                width: swipeView.width                height: swipeView.height                Button{                    text: "hello"                    onClicked: {                        ff++;                        if(ff%2==0)                        {                            loadButton()                        }else{                            loadImg()                        }                    }                    function loadButton() {                        var obj = Qt.createComponent("Text.qml");                        if (obj.status == Component.Ready) {                            var txt = obj.createObject(grid);                         }                    }                    function loadImg() {                        var obj = Qt.createComponent("Ani.qml");                        if (obj .status == Component.Ready) {                            var img = obj .createObject(grid);                        }                    }                }                Button{                    text: "hello"                }                Button{                    text: "hello"                }                Button{                    text: "hello"                }                Button{                    text: "hello"                }            }            MouseArea{                onClicked: {                    parent.loadButton()                }            }        }    }    footer: TabBar {        id: tabBar        currentIndex: swipeView.currentIndex        TabButton {            text: qsTr("First")        }        TabButton {            text: qsTr("Second")        }    }}

这里写图片描述

简化:Gobal.js

**Gobal.js.pragma libraryvar Component_Ready =1;function  createxx(file,parent){    var component = Qt.createComponent(file);    if (component.status == Component_Ready) {        var button = component.createObject(parent);        return  button;    }    return null;}***********import "Gobal.js"   as  Helper  function loadButton() {                      var obj =   Helper.createxx("Button.qml",grid);                         if(obj!=null)                        {                            obj.color ="red"                        }                     }

2.使用createQmlObject创建,不建议使用

0 0