Noopty
Noopty

Reputation: 167

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

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

Upvotes: 1

Views: 1984

Answers (3)

Romain Pokrzywka
Romain Pokrzywka

Reputation: 210

As p-a-o-l-o pointed out in his answer, you're likely building out-of-source, so your index.html file has to be in the folder where content.exe is created, not in the source folder.

To make this less complicated, and safer, Qt supports embedding files in the .exe via Qt Resource files (.qrc). These can easily be created in Qt Creator, and once added to the project, the embedded files are accessed via a qrc:/// prefix.

So in your sample code, after adding a .qrc file to your project and adding index.html to it, you would adjust your code like this:

view.setUrl(QUrl(QStringLiteral("qrc:///index.html")));

This has the advantage of working regardless of build type or location, and it's a lot simpler than trying to add a file copy step to your project file (or to manually copy the file each time)

Upvotes: 0

p-a-o-l-o
p-a-o-l-o

Reputation: 10057

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

Upvotes: 3

L.S.
L.S.

Reputation: 506

From http://doc.qt.io/qt-5/qurl.html

qDebug() << QUrl("main.qml").isRelative();          // true: no scheme
qDebug() << QUrl("qml/main.qml").isRelative();      // true: no scheme
qDebug() << QUrl("file:main.qml").isRelative();     // false: has "file" scheme
qDebug() << QUrl("file:qml/main.qml").isRelative(); // false: has "file" scheme

Try: view.setUrl(QUrl(QStringLiteral("index.html")));

Upvotes: 0

Related Questions