QQuickWindow不拥有自己的任何上下文属性,因此无法使用它设置上下文属性.
正如消息所解释的那样,QQuickView需要一个继承自QQuickItem的QML根对象,这意味着根可以是Rectangle,Item等,但不是ApplicationWindow或Window,因为它们不是从QQuickItem继承的.如果您可以将根对象更改为Rectangle,您可以创建不同的QQuickView实例来实现目标,因为如果您不提供现有的QQmlEngine,每个QQuickView都会创建自己的QQmlEngine.
QQmlApplicationEngine实际上是从QQmlEngine继承的,因此每个实例都有自己的根上下文.例如,调用以下createMain()两次将创建两个具有单独引擎的窗口,单独的控制器和单独的rootContext:
void foo::createMain() {
//TODO: Set a proper parent to myController
QMainController* myController = new QMainController(0,m_autenticado);
QQmlApplicationEngine* engine = new QQmlApplicationEngine(this);
engine->rootContext()->setContextProperty("MyController", myController);
engine->load(QUrl(QStringLiteral("qrc:///newPage.qml")));
QQuickWindow* window = qobject_cast(engine->rootObjects().at(0));
window->showFullScreen();
}
如果您不想创建QQmlAppicationEngine的多个副本,则可以共享一个QQmlApplicationEngine实例,并为每个窗口实例创建子上下文:
// foo.h
class foo {
private:
QQmlApplicationEngine m_engine; // can change to QQmlEngine if you prefer
}
// foo.cpp
void foo::createMain()
{
//TODO: Set a proper parent to myController
QMainController* myController = new QMainController(0,m_autenticado);
// Create a new context as a child of m_engine.rootContext()
QQmlContext *childContext = new QQmlContext(&m_engine, &m_engine);
childContext->setContextProperty("MyController", myController);
QQmlComponent *component = new QQmlComponent(&m_engine, &m_engine);
component->loadUrl(QUrl("qrc:///qml/newPage.qml"));
// Create component in child context
QObject *o = component->create(childContext);
QQuickWindow* window = qobject_cast(o);
window->show();
}
如果没有使用QQmlApplicationEngine的功能,当然可以将QQmlApplication更改为QQmlEngine.