[SOLVED] Loading QML from QString variable

Issue

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?

Solution

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

Answered By – Flitzekatze

Answer Checked By – Mary Flores (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *