Search code examples
qmlqt5qtvirtualkeyboard

QObject::findChildren() for QML object finding


I have an QML form with QQuickApplicationWindow. I need to get QQuickItem pointers on BaseKey elements of QtVirtualKeyboard (it's implementation is placed in separate QML file and loads with Loader of layout when program executes), but it has dynamical (runtime) type like this BaseKey_QMLTYPE_XX, where "XX" is a changeable number.

I found QObject::findChildren() function http://doc.qt.io/qt-4.8/qobject.html#findChild, but i cant find out number "XX" in typename.

How can i find QQuickItem pointer on BaseKey from C++ code?


Solution

  • BaseKey_QMLTYPE_XX looks like what you'd get if you printed the object (print(myObject)). I think that comes from QMetaObject::className().

    If the object doesn't have an objectName set, you won't be able to find it using findChild() (unless you have access to the C++ type and there's only one object of that type).

    I have a hacky test helper function that does something similar to what you're after:

    QObject *TestHelper::findPopupFromTypeName(const QString &typeName) const
    {
        QObject *popup = nullptr;
        foreach (QQuickItem *child, overlay->childItems()) {
            if (QString::fromLatin1(child->metaObject()->className()) == "QQuickPopupItem") {
                if (QString::fromLatin1(child->parent()->metaObject()->className()).contains(typeName)) {
                    popup = child->parent();
                    break;
                }
            }
        }
        return popup;
    }
    

    You could adapt this to iterate over the children of an object that you pass in. There are a couple more changes than that to get it to work, but the general idea is there.