问题
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