Search code examples
c++qtpathqtwebengineqwebengineview

Reading file from working directory QtWebEngine


Hello I am trying to set the QWebEngine URL to an index.html file that is placed in the working directory. I am trying to use the file by setting the URL to ./index.html but it cant seem to find the file.

Here is where my files are placed

  • content (Work directory)

    • main.cpp
    • content.pro
    • index.html

How can i open index.html through the QWebEngine without using the full system path?

here is my code

#include <QApplication>
#include <QWebEngineView>

int main(int argc, char *argv[])
{
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
    QApplication app(argc, argv);

    QWebEngineView view;
    view.setUrl(QUrl(QStringLiteral("file:///./index.html")));
    view.resize(1024, 750);
    view.show();

    return app.exec();
}

Solution

  • Try moving the html file to your project build directory (you're currently keeping it inside the source directory). Then you can build your URL this way:

    QUrl url = QUrl::fromLocalFile(QDir::currentPath() + "/index.html");
    

    and set it to the view:

    QWebEngineView view;
    view.setUrl(url);
    view.resize(1024, 750);
    view.show();