通过 setOfflineStoragePath 设置本地存储位置

Setting LocalStorage Location via setOfflineStoragePath

我正在尝试为我的 QML 应用程序设置 LocalStorage 位置 (sqlite db),但是一旦我重建 运行 应用程序,我仍然看不到子文件夹、INI 文件和在所需位置(在资源文件夹中的子文件夹中)创建的 sqlite 数据库。这是我的 main 文件中的内容。
感谢任何人 pint 我在这里做错了什么?

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <QString>
#include <QDebug>
#include <QDir>

int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);

    QQmlApplicationEngine engine;
    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
    //engine.setOfflineStoragePath("qrc:/");
    auto offlineStoragePath = QUrl::fromLocalFile(engine.offlineStoragePath());
    engine.rootContext()->setContextProperty("offlineStoragePath", offlineStoragePath);

    QString customPath = "qrc:/OffLineStorage";

    QDir dir;
    if(dir.mkpath(QString(customPath))){
        qDebug() << "Default path >> "+engine.offlineStoragePath();
        engine.setOfflineStoragePath(QString(customPath));
        qDebug() << "New path >> "+engine.offlineStoragePath();
    }


    return app.exec();
}

通过查看您问题中的代码片段,一切看起来都很好。
无论如何,您应该验证以下行是否确实如您预期的那样 returns true

dir.mkpath(QString(customPath)

如果不是,则 if 语句的主体在任何情况下都不会执行,因此永远不会调用 setOfflineStoragePath
作为提示,使用 qrc:/OffLineStorage 作为存储路径似乎不是一个好主意。我不确定它是否会在生产环境中运行一次(待检查,听起来很奇怪,但它可以运行)。

尝试在 engine.load 之前使用 engine.setOfflineStoragePath

Using qrc:/OffLineStorage as a path for your storage doesn't seem to be a good idea. I'm not sure it will work once in the production environment

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <QString>
#include <QDebug>
#include <QDir>

int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);

    QQmlApplicationEngine engine;

    QString customPath = "qrc:/OffLineStorage";  
    QDir dir;
    if(dir.mkpath(QString(customPath))){
        qDebug() << "Default path >> "+engine.offlineStoragePath();
        engine.setOfflineStoragePath(QString(customPath));
        qDebug() << "New path >> "+engine.offlineStoragePath();
    }

    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
    engine.clearComponentCache();
    if (engine.rootObjects().isEmpty())
        return -1;

    return app.exec();
}