我想运行QML组件列表并选择一种类型:
for (var i = 0; i < controls.children.length; ++i) {
if ( typeof (controls.children[i].height) == "QDeclarativeRectangle")
{
// do stuff
}
}
Run Code Online (Sandbox Code Playgroud)
如何实现这一目标?
Jul*_*usG 19
你不能直接使用typeof,因为它总是会将你的'object'作为任何QML元素的类型返回.但是你可以使用几种替代方案.一种是将每个元素的objectName设置为其类型,并在循环中检查它或定义属性并检查该属性.这将需要更多的工作,但您可以创建具有此属性的qml元素,而不是在需要的地方使用它.这是一个示例代码:
Rectangle {
id: main
width: 300; height: 400
Rectangle {
id: testRect
objectName: "rect"
property int typeId: 1
}
Item {
id: testItem
objectName: "other"
}
Component.onCompleted: {
for(var i = 0; i < main.children.length; ++i)
{
if(main.children[i].objectName === "rect")
{
console.log("got one rect")
}
else
{
console.log("non rect")
}
}
for(i = 0; i < main.children.length; ++i)
{
if(main.children[i].typeId === 1)
{
console.log("got one rect")
}
else
{
console.log("non rect")
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
小智 12
从Qt 5.10开始,您最终可以使用instanceOf来检查变量是否属于某种QML类型:https://v-play.net/updates/v-play-2-15-0-qt-5-10-qt -creator-4-5-支撑火力数据结构和-查询#QT-5-10-QML-枚举的instanceof
import VPlayApps 1.0
import QtQuick 2.0
App {
// two QML items, used for type checking
Item { id: testItem }
Rectangle { id: testRect }
// function to check wheter an item is a Rectangle
function isRectangle(item) {
return item instanceof Rectangle
}
// type check example
Component.onCompleted: {
console.log("testItem is Rectangle? "+isRectangle(testItem))
console.log("testRect is Rectangle? "+isRectangle(testRect))
}
}
Run Code Online (Sandbox Code Playgroud)
jic*_*chi 11
这是使用toString()的另一种方法(可能无法移植到未来版本的QML):
function qmltypeof(obj, className) { // QtObject, string -> bool
// className plus "(" is the class instance without modification
// className plus "_QML" is the class instance with user-defined properties
var str = obj.toString();
return str.indexOf(className + "(") == 0 || str.indexOf(className + "_QML") == 0;
}
...
for (var i = 0; i < controls.children.length; ++i) {
if (qmltypeof(controls.children[i].height, "QDeclarativeRectangle"))
{
// do stuff
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12529 次 |
| 最近记录: |