Jiří Maier
Jiří Maier

Reputation: 197

Loading QML from QString variable

Is it possible to use QQuickwidget::setSource() with variable (QString or QByteArray)?

I know that I can load a file (or resource): ui->quickWidget->setSource(QUrl::fromLocalFile(":/qml/Example.qml"));

But if I have the qml code stored in a variable, I could only solve it by first writing to a file on disk and loading that file. Can it be done directly?

Upvotes: 0

Views: 592

Answers (3)

Guest
Guest

Reputation: 11

Assume "code" is QByteArray and contains QML code and "view" is either QQuckView or QQuickWidget class, then:

QUrl dataurl(code.toPercentEncoding().prepend("data:,"));
view.setSource(dataurl);
view.show();

Upvotes: 1

user1095108
user1095108

Reputation: 14603

If you go for the file approach, consider using The Qt Resource System. I wrote a nice example. But you don't have to. Another possible approach is QQmlNetworkAccessManagerFactory, where you simulate loading qml from a network, but load it from a string instead, but you could load it from anywhere, say from a .zip file. Lastly, there seems to be a direct way and don't forget you can do the same from QML itself.

Upvotes: 0

Flitzekatze
Flitzekatze

Reputation: 46

Maybe with the Help of a Temporary file?

https://doc.qt.io/qt-5/qtemporaryfile.html

Something like this(i dont have much time so i just did something dirty):

QQmlApplicationEngine engine;
QString qmlFile =
        QString("import QtQuick 2.15\n")
        .append("import QtQuick.Window 2.12\n")
        .append("import QtQuick.Controls 2.12\n")
        .append("Window {\n")
        .append("id: root\n")
        .append("width: 640\n")
        .append("height: 480\n")
        .append("visible: true\n")
        .append("color: 'green'\n")
        .append("}");
QTemporaryFile file;
if(file.open())
{
    file.write(qmlFile.toUtf8());
}
file.close();
engine.load(file.fileName());

Upvotes: 1

Related Questions