Search code examples
c++qtcmakeincludeqt6

How to include webview in existing Qt project?


I am trying to include one of the following libraries:

#include <QtWebView>
#include <QWebView>
#include <QtWebEngineWidgets>
#include <WebEngineCore>
#include <QtWebEngine>

Each time I add one of its includes an error appears in my code. However, I use Qt 6.3.1 and I find files that correspond to the includes in my system installation folder under macOS. I use a cmake in my qt project and not a file.pro or qmake.

Ultimately, I want to display a web form in my UI.


Solution

  • You need to make sure that you install the QtWebEngine module when installing Qt.

    enter image description here

    Then, in your CMakeLists.txt, you would write something like this below.

    Please note that you should use versionless targets as recommended by the Qt Project, i.e. do not use Qt6::WebEngineWidgets as that would have portability issues.

    find_package(Qt6 COMPONENTS WebEngineWidgets REQUIRED)
    target_link_libraries(YourTarget Qt::WebEngineWidgets)
    add_executable(YourTarget main.cpp)
    

    Then, you can just write something like this in your main.cpp:

    #include <QApplication>
    #include <QWebEngineView>
    
    int main(int argc, char *argv[])
    {
        QApplication app(argc, argv);
    
        QWebEngineView view;
        view.setUrl(QUrl(QStringLiteral("https://www.qt.io")));
        view.show();
    
        return app.exec();
    }
    

    Please refer to the official examples for further details.