How to get object by objectName in Qml from javasc

2019-08-21 11:41发布

问题:

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

回答1:

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++.

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.

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.

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.

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.

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.



标签: qml qt5