Home > Blockchain >  Loading QML from QString variable
Loading QML from QString variable

Time:02-14

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?

CodePudding user response:

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

CodePudding user response:

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 anwhere, say from a .zip file.

  • Related