WebEngine Qt Quick 最小范例

以 Qt Quick 集成 Qt WebEngine 显示网页。

WebEngine Qt Quick Minimal Example 演示如何使用 WebEngineView item 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 ,打开 欢迎 模式,然后选择范例从 范例 。更多信息,拜访 构建和运行范例 .

C++ 代码

main.cpp we use only the QGuiApplication and QQmlApplicationEngine classes. We also include qtwebengineglobal.h to be able to use QtWebEngineQuick::initialize .

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QtWebEngineQuick/qtwebenginequickglobal.h>
					

main function we first set the QCoreApplication::organizationName property. This affects the locations where Qt WebEngine stores persistent and cached data (see also WebEngineProfile::cachePath and WebEngineProfile::persistentStoragePath ).

Next, we call QtWebEngineQuick::initialize , which makes sure that OpenGL contexts can be shared between the main process and the dedicated renderer process ( QtWebEngineProcess ). This method needs to be called before any OpenGL context is created.

Then we create a QQmlApplicationEngine , and tell it to load main.qml Qt 资源系统 .

最后, QGuiApplication::exec () launches the main event loop.

int main(int argc, char *argv[])
{
    QCoreApplication::setOrganizationName("QtExamples");
    QCoreApplication::setAttribute(Qt::AA_ShareOpenGLContexts);
    QtWebEngineQuick::initialize();
    QGuiApplication app(argc, argv);
    QQmlApplicationEngine engine;
    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
    return app.exec();
}
					

QML 代码

main.qml we create the top level window, set a sensible default size and make it visible. The window will be filled by a WebEngineView item loading the Qt Homepage .

import QtQuick
import QtQuick.Window
import QtWebEngine
Window {
    width: 1024
    height: 750
    visible: true
    WebEngineView {
        anchors.fill: parent
        url: "https://www.qt.io"
    }
}
					

要求

The example requires a working internet connection to render the Qt Homepage . An optional system proxy should be picked up automatically.

范例工程 @ code.qt.io