How to do a quot;is_aquot;, quot;typeofquot; or instanceof in QML?(如何做一个“is_a、“typeof还是 QML 中的 instanceof?)
问题描述
我想遍历 QML 组件列表并选择一种类型:
I want to run through a list of QML components and choose one type:
for (var i = 0; i < controls.children.length; ++i) {
if ( typeof (controls.children[i].height) == "QDeclarativeRectangle")
{
// do stuff
}
}
如何做到这一点?
推荐答案
你不能直接使用 typeof 因为它总是会返回你 'object' 作为任何 QML 元素的类型.但是,您可以使用多种替代方法.一种是将每个元素的 objectName 设置为其类型并在循环中检查它或定义一个属性并检查该属性.这将需要更多的工作,但您可以创建具有此属性的 qml 元素,而不是在需要的任何地方使用它.这是一个示例代码:
You can't use typeof for this directly because it will always return you 'object' as a type of any QML element. There are several alternatives however that you could use. One is setting the objectName of the each element to its type and check that in your loop or define a property and check for that property. This will require a bit more work but you could create your qml element that has this property and than use it wherever you need it. Here is a sample code:
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")
}
}
}
}
这篇关于如何做一个“is_a"、“typeof"还是 QML 中的 instanceof?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何做一个“is_a"、“typeof"还是 QML 中的 instanceof?
基础教程推荐
- 我可以在浏览器中与Babel一起使用ES模块,而不捆绑我的代码吗? 2022-01-01
- 自定义 XMLHttpRequest.prototype.open 2022-01-01
- Vue 3 – <过渡>渲染不能动画的非元素根节点 2022-01-01
- 如何使用TypeScrip将固定承诺数组中的项设置为可选 2022-01-01
- 直接将值设置为滑块 2022-01-01
- Chart.js 在线性图表上拖动点 2022-01-01
- html表格如何通过更改悬停边框来突出显示列? 2022-01-01
- Electron 将 Node.js 和 Chromium 上下文结合起来意味着 2022-01-01
- 用于 Twitter 小部件宽度的 HTML/CSS 2022-01-01
- 如何使用JIT在顺风css中使用布局变体? 2022-01-01