How can I get access to object of `QQmlApplicationEngine` inside a `QQuickItem` derived class?

妖精的绣舞 提交于 2019-12-24 19:19:30

问题


The variable engine in the following typical main function of a QtApp is a valid instance of QQmlApplicationEngine.

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

  QQmlApplicationEngine engine;
  engine.load(QUrl(QStringLiteral("qrc:/qml/main.qml")));

  return app.exec();
}

Is it possible to get access to object of QQmlApplicationEngine inside a function of a QQuickItem derived class? If yes, how?

class TestItem : public QQuickItem {
public:
  TestItem();
  SomeMethod() {
     // Is it possible to get access to QQmlApplicationEngine here somehow ?
  }
}

Note that TestItem is registered on the qml side & displayed on the main window. I know that I can pass the QQmlApplicationEngine from main method. But, I have a hunch that because my TestItem is part of the window & holds the context. There should be a way to get an object or pointer to QQmlApplicationEngine without having to pass from main method ?

The objective: Using QQmlApplicationEngine I can get access to QQuickItems in my main.qml by doing so:

QQuickItem *some_quick_item = qml_engine->rootObjects()[0]->findChild<QQuickItem*>("SomeQuickItem");

So for doing this, I want to the QQmlApplicationEngine. If theres a way to get access to other QQuickItems from inside of one then please suggest.


回答1:


You can use this static function:

QQmlEngine::contextForObject(this)->engine();

Of course, it might be a good idea whether contextForObject() returns a valid pointer before you try and invoke engine() for it.

Then you can use qobject_cast<QQmlApplicationEngine*>(engine) which should give you the desired pointer as long as your application is indeed a QQmlApplicationEngine based one.



来源:https://stackoverflow.com/questions/45700420/how-can-i-get-access-to-object-of-qqmlapplicationengine-inside-a-qquickitem

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!