0

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?

3 Answers 3

1

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());
Sign up to request clarification or add additional context in comments.

Comments

1

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();

Comments

0

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.

1 Comment

As far as I know, the resources can not be changed on runtime, but I need that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.