QWebEngineView路径问题-将HTML/JS/CSS添加到qrc文件中

通过QRC管理HTML/JS/CSS文件

gitee-QWebEngineView C++和js交互 / github-QWebEngineView C++和js交互 中介绍了QWebEngine,QWebChannel的简单使用。

HTML/JS/CSS文件放入到程序执行目录中,其主要代码如下:

1
2
3
QWebEngineView* view = new QWebEngineView(this);
view->load(QUrl::fromLocalFile(qApp->applicationDirPath() + "/test.html"));
view->show();
  1. 不方便git管理。

  2. 客户可以查看/修改前端代码。

可通过将HTML/JS/CSS文件放入qrc中解决改问题。先将相关文件添加到qrc中,然后:

1
view->load(QUrl("qrc:/test.html"));
  1. 需要将HTML/JS/CSS文件都放入到qrc中,而不是只放HTML文件。
  2. 直接使用qrc:形式的路径,不要使用QUrl::fromLocalFile("qrc:/test.html")

清理缓存:

1
2
3
4
5
6
7
8
9
10
11
QWebEngineView* view = new QWebEngineView(this);

QWebEngineSettings * webEngineSettings = view->settings();
webEngineSettings->setAttribute(QWebEngineSettings::LocalStorageEnabled, false);
QWebEngineProfile * engineProfile = view->page()->profile();
engineProfile->clearHttpCache();
QString cachePath = engineProfile->cachePath();
QDir cachePathDir(cachePath);
if (cachePathDir.exists()) {
cachePathDir.removeRecursively();
}