2

I'd like to use an ApplicationWindow as a main file and be able to switch to other QML files from C++ with QQuickView::setSource(const QUrl & url). Basically it would do this:

start-up => loads main.qml (ApplicationWindow) => click on help button => C++ loads help.qml file => etc.

int main(int argc, char *argv[])
{
    QApplication app{argc, argv};
    CustomQQuickView view;

    view.setSource(QUrl{"qrc:/main.qml"});
    view->show();

    return app.exec();
}

main.qml

ApplicationWindow
{
    visible: true
    width: 640
    height: 480

    Loader
    {
        anchors.fill: parent
        id: mainPageLoader
    }

    Button
    {
        text: "Help"
        onClicked: { mainPageLoader.source = "help.qml"}
    }
}

(I am wondering if the Loader here is really necessary here)

However QQuickView only supports loading of root objects that derive from QQuickItem. Therefore it doesn't work with ApplicationWindow.

I'm thinking about using QQmlApplicationEngine instead of QQuickView but the usage seems different, this class being only equipped with QQmlApplicationEngine::load(const QUrl & url)

What would be the best course of action for my purpose? Do I really need an ApplicationWindow in my main.qml file?

4

1 回答 1

3

QQmlApplicationEngine按照您的建议使用,并main.qml按照您的说法使用,但使用内容页面 URL 设置 C++ 的上下文属性,例如help.qml- 然后绑定到加载器的源属性中的此上下文属性。

这是从 C++ 控制 QML 的正常方式 - 公开上下文属性或具有属性的单例对象,从 C++ 驱动它们,并让 QML 绑定响应更改。

于 2016-02-18T22:35:02.643 回答