I am using Qt WebEngine 5.14 on Manjaro Linux.
I want to open local html file with id, but the following code is not working. It says file is not found.
Here is code:
#include <QApplication>
#include <QWebEngineView>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QWebEngineView view;
//open remote html with id is working
//view.load(QUrl("https://cges30901.github.io/test/hash/test#p3"));
//open local file is working
//view.load(QUrl::fromLocalFile(a.applicationDirPath()+"/test.html"));
//open local file with id is not working
view.load(QUrl::fromLocalFile(a.applicationDirPath()+"/test.html#p3"));
view.show();
return a.exec();
}
This is test.html:
<!--?xml version='1.0' encoding='utf-8'?-->
<!DOCTYPE html>
<html lang="zh-hant" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8"/>
<title>test</title>
</head>
<body>
<p id="p1">This is paragraph 1</p>
<p id="p2">This is paragraph 2</p>
<p id="p3">This is paragraph 3</p>
<p id="p4">This is paragraph 4</p>
<p id="p5">This is paragraph 5</p>
<p id="p6">This is paragraph 6</p>
<p id="p7">This is paragraph 7</p>
<p id="p8">This is paragraph 8</p>
<p id="p9">This is paragraph 9</p>
<p id="p10">This is paragraph 10</p>
<p id="p11">This is paragraph 11</p>
<p id="p12">This is paragraph 12</p>
<p id="p13">This is paragraph 13</p>
<p id="p14">This is paragraph 14</p>
<p id="p15">This is paragraph 15</p>
<p id="p16">This is paragraph 16</p>
<p id="p17">This is paragraph 17</p>
<p id="p18">This is paragraph 18</p>
<p id="p19">This is paragraph 19</p>
</body>
</html>
Can someone teach me how to open local html file with id?
Problem
You are trying to create an url from a local file with the path .../test.html#p3
. Calling QUrl::fromLocalFile
results in an url like file:///<path>/test.html%23p3
which fails to load.
Solution
First convert the local path into a URL. Add the fragment to the resulting URL and display it:
QUrl url = QUrl::fromLocalFile(a.applicationDirPath() + "/test.html");
url.setFragment("p3");
view.load(url);
Then it works as intended.