[英]adding a class with condition using qml
I have an item and I want to add a class into it, this one depend on a variable 我有一个项目,我想在其中添加一个类,这个取决于变量
import "class1"
import "class2"
Item { id: myID
property variant myVar: 0;
anchors.fill: parent;
function update() {
switch(myID.myVar)
{
case 0:
class1 {
anchors.fill: parent;
}
break;
case 1:
class2 {
anchors.fill: parent;
}
break;
}
}
} }
Actually this is a wrong code, any way to do that ? 其实这是一个错误的代码,可以这样做吗?
Thank you. 谢谢。
QML and JavaScript intermesh, but what you're trying to use is QML class instantiation syntax in JavaScript context - it won't ever work that way. QML和JavaScript相互啮合,但是您要使用的是JavaScript上下文中的QML类实例化语法-它将永远不会那样工作。 Once a QML file is loaded, all the class instances defined therein are already instantiated.
加载QML文件后,其中定义的所有类实例都已实例化。
You need to define two components, and use a loader to dynamically create one of them. 您需要定义两个组件,并使用加载程序动态创建其中之一。 So, something like the below.
因此,如下所示。 I haven't tested it, but it should steer you in the right direction, I hope.
我尚未对其进行测试,但是我希望它可以引导您朝着正确的方向发展。
import "class1"
import "class2"
Item {
id: myItem
property variant myVar: 0;
anchors.fill: parent;
Component {
id: compClass1
class1 {
anchors.fill: myItem;
}
}
Component {
id: compClass12
class2 {
anchors.fill: myItem;
}
}
Loader { id: myLoader }
function update() {
switch(myID.myVar) {
case 0:
myLoader.sourceComponent = compClass1;
break;
}
case 1:
myLoader.sourceComponent = compClass2;
break;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.