本文介绍了使用QML在加载器中调用类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
其实我有这个代码:
import "class1"
import "class2"
Item {
id: myItem
property variant myVar: 0;
anchors.fill: parent;
Component {
id: compClass1
class1 { id: class1ID
anchors.fill: myItem;
}
}
Component {
id: compClass2
class2 {
anchors.fill: myItem;
}
}
Loader { id: myLoader }
function update() {
switch(myID.myVar) {
case 0:
myLoader.sourceComponent = compClass1;
classID.myFunction();
break;
case 1:
myLoader.sourceComponent = compClass2;
break;
}
}
}
当我想调用一个函数时,我得到一个错误的问题:TypeError:表达式的结果'class1ID.myFunction'[undefined]不是一个函数。
The problem when I want to call a function, I get an error :TypeError: Result of expression 'class1ID.myFunction' [undefined] is not a function.
PS:class'class1'has have a function called'myFunction()'
P.S : the class 'class1' have already a function called 'myFunction()'
推荐答案
您需要使用 class1
函数在 Loader c>。下面是一个示例:
If you want to access your
class1
function you need to use the item
property on your Loader
. Here is an example showing this:
Rectangle {
id: myItem
width: 300
height: 300
color: "yellow"
Component {
id: compClass1
Rectangle {
id: class1ID
color: "blue"
width: myItem.width
height: myItem.height
function function1() {
console.log("I am in class1");
}
}
}
Component {
id: compClass2
Rectangle {
color: "red"
width: myItem.width
height: myItem.height
function function1() {
console.log("I am in class2");
}
}
}
Loader { id: myLoader }
MouseArea {
property int nbClicks: 0
anchors.fill: parent
onClicked: {
if(nbClicks % 2 == 0 ) {
myLoader.sourceComponent = compClass1;
} else {
myLoader.sourceComponent = compClass2;
}
myLoader.item.function1();
nbClicks++;
}
}
}
这篇关于使用QML在加载器中调用类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!