如何通过javascript从Qml中的objectName获取对象? [英] How to get object by objectName in Qml from javascript?

查看:41
本文介绍了如何通过javascript从Qml中的objectName获取对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用 findChild() 在 C++ 中查找对象,但从 javascript 中查找?

How to find object like in C++ with findChild(), but from javascript?

推荐答案

在 QML 端,您通常无法访问 Qt/C++ 端的父/子关系,而只能访问可视化的父/子关系孩子的关系,你将需要求助于 C++.

As on the QML-side you usually have no access to the parent/child-relationships of the Qt/C++-side, but only to the visual parent/child-relationship, you will need to resort to C++.

你可以例如创建一个对象,该对象公开一个方法,该方法接受一个 QObject 和一个名称,并调用该对象的函数 findChild.

You could e.g. create a object, that exposes a method which takes a QObject, and a name and calls the function findChild of this object.

如果你只想找到一个可视化的孩子,你可能只是在 JS 中的可视化树上实现一个递归 bfs 并调用它.

If you only want to find a visual child, you might just implement a recursive bfs over the visual tree in JS and call this.

但正如我在我的评论中所说:如果你需要这个,你可能在其他地方搞砸了,而应该考虑一种没有findChild()的方法.不推荐在 C++ 中使用它,在 QML 中也不推荐使用它.
由于它是递归搜索,因此它会尽最大努力降低您的性能.一个 UI 很容易包含一千个元素,你需要一直比较 string .此外,您会通过偷偷地访问您没有告诉任何人您依赖的东西来谎报依赖关系.

But as I said in my comment: If you need this, you probably messed up at some other place and should rather think about a way to do it, without findChild(). Using it is not recommended in C++, and is certainly not so in QML.
As it is a recursive search it will do its best in killing your performance. A UI contains easily a thousand elements and you would need to compare the strings all the time. Further you would lie about the dependencies by sneakingly access things you don't tell anyone you are depending on.

objectName 和调用 findChild 的对象可能不在你代码的同一个逻辑部分,所以它很容易被破坏,如果有人可能改变这个对象或objectName,而您正在搜索一个不再存在的名称.

The objectName and the object that calls findChild might not be in the same logical part of your code, so it is easily broken, if someone might change this object or the objectName, and you are searching for a name that does not exist anymore.

此外,如果您找到具有名称的对象 - 并且可能是正确的类型 - 仍然不能保证它是正确的对象,因为 objectNames 不一定是唯一的.

Additionally, if you found an object with the name - and possibly the right type - there is still no guarantee, it is the right object, as the objectNames are not necessarily unique.

总而言之,访问这样的对象并不是最好的设计 - 这可能很难.

All in all, it is not the best design, to access objects like that - tough it might be possible.

免责声明:我还没有尝试过我提出的解决方案,因为我不想在上面浪费时间.

Disclaimer: I have not tried out my proposed solution, as I don't want to waste my time on it.

这篇关于如何通过javascript从Qml中的objectName获取对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆