NG_
NG_

Reputation: 7181

How to load qml file from resources, using QtQuick 2 Controls

I have created Qt Quick 2 Controls project, added resource, placed my qml-file inside resource and added alias to this file. Now I'm wondering, why does next code can't load qml-file as main qml-file:

#include <QDebug>
#include <QFile>
#include <QByteArray>
#include "qtquick2controlsapplicationviewer.h"

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

    QString fileInResource(":main/mainQml");

    QFile f(fileInResource);
    if (!f.exists()) {
        qDebug() << "No file";
    } else {
        f.open(QIODevice::ReadOnly);
        qDebug() << f.readAll();
    }

    QtQuick2ControlsApplicationViewer viewer;
    viewer.setMainQmlFile(fileInResource);
    viewer.show();

    return app.exec();
}

Since in case of QFile usage, it reads file correct and output whole file, but viewer said:

file:///path/:main/mainQml:-1 File not found

QQmlComponent: Component is not ready Error: Your root item has to be a Window.`

How to make viewer load my qml-file?


UPD: Added minimal working example -- download it here

Upvotes: 3

Views: 6595

Answers (2)

bulldog68
bulldog68

Reputation: 307

No file file:///path/qrc:/main/mainQml <-

try change the code like below and make sure main.qml file exists in resource .qrc file

QQmlApplicationEngine engine;
    engine.rootContext()->setContextProperty("utils", &qmlUtils);
    engine.load(QUrl(QStringLiteral("qrc:///main.qml")));

or like this if you are not using the QQmlApplicationEngine

 Application app(argc, argv);
 QString fileInResource("qrc:///main.qml");

Upvotes: 2

Sergei Eliseev
Sergei Eliseev

Reputation: 171

The problem is in

void QtQuick2ApplicationViewer::setMainQmlFile(const QString &file)

It uses

setSource(QUrl::fromLocalFile(d->mainQmlFile));

for setting source, and QUrl::fromLocalFile messes up the path. Just change it to

setSource(QUrl(d->mainQmlFile));

and everything works.

UPD:

In your example it's actually component.loadUrl(QUrl::fromLocalFile(d->mainQmlFile));, line 80.

Upvotes: 3

Related Questions