从 QString 变量加载 QML

Loading QML from QString variable

是否可以将 QQuickwidget::setSource() 与变量(QString 或 QByteArray)一起使用?

我知道我可以加载文件(或资源):ui->quickWidget->setSource(QUrl::fromLocalFile(":/qml/Example.qml"));

但是如果我将 qml 代码存储在一个变量中,我只能通过首先写入磁盘上的文件并加载该文件来解决它。可以直接做吗?

也许借助于临时文件?

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

类似这样的事情(我没有太多时间所以我只是做了一些肮脏的事情):

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

如果您选择文件方式,请考虑使用 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