WebEngine Widgets Minimal Example 演示如何使用 QWebEngineView to render a web page. It shows the minimum amount of code needed to load and display an HTML page, and can be used as a basis for further experimentation.
要运行范例从 Qt Creator ,打开 欢迎 模式,然后选择范例从 范例 。更多信息,拜访 构建和运行范例 .
We first define a
commandLineUrlArgument
function that returns the URL to open. This is either the first positional argument given on the command line, or
https://www.qt.io
as a fallback.
#include <QApplication> #include <QWebEngineView> QUrl commandLineUrlArgument() { const QStringList args = QCoreApplication::arguments(); for (const QString &arg : args.mid(1)) { if (!arg.startsWith(QLatin1Char('-'))) return QUrl::fromUserInput(arg); } return QUrl(QStringLiteral("https://www.qt.io")); }
在
main
function we first set the
QCoreApplication::organizationName
property. This affects the locations where Qt WebEngine stores persistent and cached data (see also
QWebEngineProfile::cachePath
and
QWebEngineProfile::persistentStoragePath
).
We also set the Qt::AA_EnableHighDpiScaling attribute. This lets the web view automatically scale on high-dpi displays.
Next, we instantiate a
QApplication
和
QWebEngineView
. The URL to load is taken from
commandLineUrlArgument
and loaded by calling
QWebEngineView::setUrl
. The view widget is given a reasonable default size, and shown. Finally,
QApplication::exec
() launches the main event loop.
int main(int argc, char *argv[]) { QCoreApplication::setOrganizationName("QtExamples"); QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling); QApplication app(argc, argv); QWebEngineView view; view.setUrl(commandLineUrlArgument()); view.resize(1024, 750); view.show(); return app.exec(); }
The example requires a working internet connection to render the Qt Homepage . An optional system proxy should be picked up automatically. However, for proxies that require a username or password, you need to connect to QWebEnginePage::proxyAuthenticationRequired .
Qt WebEngine Widgets 使用 Qt Quick 场景图形 去合成页面。因此,需要 OpenGL 支持。