简体   繁体   English

如何使用C ++ API获取QML对象的id属性

[英]How to get QML object's id property using C++ API

I need to parse a QML tree and get id s of all QML objects along the way which have it. 我需要解析一个QML树并获取所有QML对象的id I noticed that id s don't behave like normal properties (see the example below) – value returned from obj->property call is an invalid QVariant . 我注意到id的行为与普通属性不同(参见下面的例子) - 从obj->property调用返回的值是一个无效的QVariant

My question is – is there a way to retrieve object's id , even in some hacky (but reproductible) way? 我的问题是 - 有没有办法检索对象的id ,即使是一些hacky(但可重现)的方式?

Simplified example: 简化示例:

main.qml: main.qml:

import QtQuick 2.9
import QtQuick.Window 2.2

Window {
    visible: true

    Item {
        id: howToGetThis
        objectName: "item"
    }
}

main.cpp: main.cpp中:

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QTimer>
#include <QDebug>

int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);

    QQmlApplicationEngine engine;
    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
    if (engine.rootObjects().isEmpty())
        return -1;

    QTimer::singleShot(1000, [&]() {
        auto item = engine.rootObjects()[0]->findChild<QObject*>("item");
        qDebug() << item->property("objectName");
        qDebug() << item->property("id");
    });

    return app.exec();
}

Output: 输出:

QVariant(QString, "item")
QVariant(Invalid)

I think what you need is: 我想你需要的是:

QString QQmlContext::nameForObject(QObject *object)

You can find the description here: https://doc.qt.io/qt-5/qqmlcontext.html#nameForObject 你可以在这里找到描述: https//doc.qt.io/qt-5/qqmlcontext.html#nameForObject

Returns the name of object in this context, or an empty string if object is not named in the context. 返回此上下文中对象的名称,如果在上下文中未指定对象,则返回空字符串。 Objects are named by setContextProperty(), or by ids in the case of QML created contexts . 对象由setContextProperty()命名,或者在QML创建的上下文中由id命名。


Based on comments received, a common pitfall is to call nameForObject using the wrong QQmlContext . 根据收到的意见,一个常见的错误是调用nameForObject使用错误QQmlContext (When that happens, you just the empty string.) To help with that, here is a more complete example: (当发生这种情况时,你只是空字符串。)为了帮助解决这个问题,这里有一个更完整的例子:

  QQuickItem* const focus_item = my_QQuickWindow->activeFocusItem();
  if (!focus_item) {
    fprintf(stderr, "no item has focus");
  } else {
    // There are many contexts in a hierarchy. You have to get the right one:
    QQmlContext* const context = qmlContext(focus_item);
    if (!context) {
      // Unsure if this branch of code is even reachable:
      fprintf(stderr, "item is not in any context?");
    } else {
      const QString focus_item_id = context->nameForObject(focus_item);
      fprintf(stderr, "focus item: %s\n", focus_item_id.toStdString().c_str());
    }
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM