1.Qt.createComponent 创建组件对象 createObject指定父元素
**Ani.Qml
AnimatedImage {
id: animation; source: "qrc:/T.gif"
width: 40
height: 40
}
**Text.Qml
Text{
width: 40
height: 40
text: "Hello"
verticalAlignment: Text.AlignBottom
}
**main.Qml
import QtQuick 2.7
import QtQuick.Controls 2.0
import QtQuick.Layouts 1.0
ApplicationWindow {
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 library
var 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创建,不建议使用