如何在 QML 中动态添加组件? [英] How to dynamically add components in QML?
本文介绍了如何在 QML 中动态添加组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图在按下按钮时动态创建一个组件,然后将其添加到当前父级.我不确定我在这里做错了什么,
I am trying to create a component on the fly when a button is pressed, then add it to the current parent. I'm not sure what I am doing wrong here,
我有这个简单的布局:
import QtQuick 2.0
import Ubuntu.Components 0.1
import "components"
import "componentCreation.js" as MyScript
/*!
rief MainView with a Label and Button elements.
*/
MainView {
// objectName for functional testing purposes (autopilot-qt5)
objectName: "mainView"
// Note! applicationName needs to match the "name" field of the click manifest
applicationName: "com.ubuntu.developer..SpritePractice"
/*
This property enables the application to change orientation
when the device is rotated. The default is false.
*/
//automaticOrientation: true
width: units.gu(100)
height: units.gu(75)
Page {
title: i18n.tr("Simple")
Column {
spacing: units.gu(1)
anchors {
margins: units.gu(2)
fill: parent
}
Button
{
text: i18n.tr("Hello World!!");
onClicked:
{
var component;
var sprite;
component = Qt.createComponent("Sprite.qml");
sprite = component.createObject(parent, {"x": 100, "y": 100});
}
}
}
}
}
这是我要添加的精灵":
Here is my "sprite" that I am trying to add:
import QtQuick 2.0
Rectangle { width: 80; height: 50; color: "red" }
如何将我正在创建的组件添加到当前父级?
How can I add the component I am creating to the current parent?
如何解决:
我使用了下面的答案并使用了 Ubuntu 文档:
I used the answer below and I used the Ubuntu documentation:
推荐答案
这里需要提供id,而不是parent.
You need to provide id here, instead of parent.
sprite = component.createObject(parent, {"x": 100, "y": 100});
尝试关注,
Page {
...
Column {
id: container
...
Button
{
text: i18n.tr("Hello World!!");
onClicked:
{
var component;
var sprite;
component = Qt.createComponent("Sprite.qml");
sprite = component.createObject(container, {"x": 100, "y": 100});
}
}
}
}
我还创建了一个示例代码, 也一样, 请看一下
I also created a sample code, which does same, Please have a look
这篇关于如何在 QML 中动态添加组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文