SoFunction
Updated on 2025-03-02

Detailed introduction to QT's QWebEngineView knowledge points

1. Introduction to QWebEngineView

QWebEngineView is a component in the Qt framework. It is a web browser engine based on the Chromium kernel. It is used to embed web page content in Qt applications and implement various web application functions. Through QWebEngineView, developers can easily integrate web browsing functions in local desktop applications, supporting modern web technologies such as HTML5, CSS3, and JavaScript.

Note: The QWebEngineView class only supports QT version 5.4 or above. Previous versions used QtWebKit. The QtWebKit class has been discarded on version 5.4 or above and cannot be used. For the QWebEngineView class, compilers that only support MSVC do not support MinGW.

Load and display the content of the web page.

Interact with JavaScript in web pages.

Listen and handle various signal slot events such as web page loading completion and loading failure.

Implement web navigation control (forward, backward, refresh) and other functions.

In Qt Quick, the corresponding function class is QQuickWebEngineView, which is used to embed Web content in QML scenarios.

For example, the basic usage of creating and loading a web page is as follows:

#include <QWebEngineView>
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    QWebEngineView view;
    (QUrl(QStringLiteral("")));
    ();

    return ();
}

The above code will create a QWebEngineView window and load the content of the website.

2. Member functions

1、QWebEngineView::QWebEngineView(QWidget *parent = Q_NULLPTR)

QWebEngineView::QWebEngineView(QWidget *parent = Q_NULLPTR)It is the constructor used in the Qt WebEngine module to create a QWebEngineView object.

ParametersparentPoint to a QWidget pointer, which is the parent window or parent control of the QWebEngineView. If no parameters are passed in (using the default value Q_NULLPTR), the QWebEngineView will become a top-level window. If a parent control is specified, the QWebEngineView will exist as a child control of the parent control and follow the life cycle and layout rules of the parent control.

In short, this code:

QWebEngineView *webView = new QWebEngineView(parentWidget);

A new QWebEngineView instance will be created and its parent control will be set toparentWidget. If you need to display a view in the window that can browse the content of the web page, this is the basic step in creating the view. You can call it laterwebView->load(QUrl(url))To load the specified webpage URL.

2、void QWebEngineView::back()

void QWebEngineView::back()is a member function in the Qt WebEngine module and is applied to the QWebEngineView class. The function of this function is to make the web browser history in QWebEngineView fall back a step, that is, to display the previous visited web page.

In actual application, if you have a QWebEngineView object (such as namedwebView), and the user has browsed several web pages in the browser control and calledwebView->back();It will return the browser to the previous page, just like clicking the "Back" button in a regular web browser.

The following is a useQWebEngineViewandback()Simple code example of a function:

#include &lt;QApplication&gt;
#include &lt;QWebEngineView&gt;
#include &lt;QUrl&gt;

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    // Create a QWebEngineView instance    QWebEngineView* webView = new QWebEngineView();

    // Load a web page    webView-&gt;load(QUrl(""));

    // Show QWebEngineView    webView-&gt;show();

    // Assuming that the user has browsed some pages, now simulate clicking the "Back" button    if (webView-&gt;history()-&gt;canGoBack()) {
        webView-&gt;back(); // Fall back to the previous page    }

    return ();
}

In this example, first, aQWebEngineViewinstance, and a web page is loaded. Then, checkwebViewIs it possible to fall back in the history of (i.e., whether there are at least two pages), and if so, callback()Functions to implement page fallback function. In practical applications, usuallyback()The call of the function is bound to a button click event for the user to manually trigger the page fallback behavior.

3、void QWebEngineView::forward()

void QWebEngineView::forward()is a member function in the Qt WebEngine module and is used in the QWebEngineView class. The function of this function is to move forward in the web browsing history, that is, to display the next visited web page.

In actual application, if you have a QWebEngineView object (e.g.webView), and the user has browsed several web pages in the browser control and is currently on the previous page of the history record, callwebView->forward();The browser will jump to the next page, just like clicking the "Forward" button in a regular web browser.

Here is a useforward()Basic examples of functions:

#include &lt;QApplication&gt;
#include &lt;QWebEngineView&gt;
#include &lt;QUrl&gt;

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    // Create a QWebEngineView instance    QWebEngineView* webView = new QWebEngineView();

    // Load an initial web page    webView-&gt;load(QUrl(""));

    // The user has browsed other pages and now assumes that he has pressed the back button to return to the previous page    if (webView-&gt;history()-&gt;canGoForward()) { // Check whether you can go to the next page        webView-&gt;back(); // Simulate first and take a step back        webView-&gt;forward(); // Then the simulation goes to the next page    }

    // Show QWebEngineView    webView-&gt;show();

    return ();
}

In this example, we first load a web page, then assume the user has done a back operation and check if it can go forward. If possible, we will callforward()function, let the browser display the next page. In real applications, usuallyforward()The function is bound to a "Forward" button click event.

4、void QWebEngineView::iconChanged(const QIcon &icon)

void QWebEngineView::iconChanged(const QIcon &icon)It is a signal of the QWebEngineView class in the Qt WebEngine module. This signal is transmitted when the loaded web icon (Favicon) changes.

This signal does not have a corresponding member function, but serves as a notification mechanism that allows you to connect to a slot function to respond to changes in web icons. For example, when you want to update the icon for a web page in the address bar or bookmark, you can do this:

QObject::connect(webView, &amp;QWebEngineView::iconChanged, [=](const QIcon &amp;newIcon){
    // Update icons in the address bar or bookmark bar    addressBar-&gt;setIcon(newIcon);
    bookmarksManager-&gt;updateBookmarkIcon(currentUrl, newIcon);
});

// Or process in slot functionconnect(webView, SIGNAL(iconChanged(QIcon)), this, SLOT(updatePageIcon(QIcon)));

//Slot functionvoid YourClass::updatePageIcon(const QIcon &amp;icon) {
    // Handle icon changes here, such as updating icons in the UI    myStatusIcon-&gt;setIcon(icon);
}

Please note that the above code shows the connection method between signals and slots in Qt 5. For Qt 5.14 and later, it is recommended to use lambda expressions orconnectThe first form of the function is to connect the signal and the slot. In Qt 4 style signal slot syntax, useSIGNALandSLOTMacro.

5、void QWebEngineView::iconUrlChanged(const QUrl &url)

void QWebEngineView::iconUrlChanged(const QUrl &url)It is a signal of the QWebEngineView class in the Qt WebEngine module. When the icon URL (favicon URL) of the web page changes, the signal will be transmitted. This signal carries a QUrl-type parameter that contains the URL of the new icon resource.

This signal is often used to monitor the update of web page favicon. When the icon URL of the web page changes, you can connect to this signal and obtain and update the corresponding icon resources according to the new URL.

For example, through the signal slot mechanism, you can capture this signal and perform corresponding actions:

QObject::connect(webView, &amp;QWebEngineView::iconUrlChanged, [&amp;](const QUrl &amp;newIconUrl){
    // The new icon URL has been changed, and the icon can be downloaded and updated according to the new URL here    // The following code is only for illustration. In actual applications, it may be necessary to download and process icon data asynchronously.    QImage iconImage = QImageReader(newIconUrl).read();
    if (!()) {
        myStatusBar-&gt;setIcon(QIcon(iconImage));
    }
});

void QWebEngineView::iconChanged(const QIcon &icon)andvoid QWebEngineView::iconUrlChanged(const QUrl &url)are two different signals of the QWebEngineView class in the Qt WebEngine module. The difference is the information provided and the processing method:

  • iconChanged(const QIcon &icon)

    • This signal is triggered when the actual content of the web page icon (favicon) changes.
    • When the web page's favicon is loaded or updated, the signal will directly pass a parsed and loaded icon object (QIcon).
    • Developers can use this icon object to update the UI directly without caring about the specific URL and loading process.
  • iconUrlChanged(const QUrl &url)

    • This signal is triggered when the favicon URL of the web page changes.
    • This signal only provides the URL address of the new icon resource, and does not provide the resolved icon data.
    • Developers need to load image resources by themselves based on this URL (for example through QImageReader and other tools), then convert them into QIcon objects, and finally update the UI.

In summary,iconChangedProvides physical data of favicon pictures, which can be directly used for interface updates; andiconUrlChangedThe URL of the image resource is provided, and the developer needs further processing to obtain the image data. In practical applications, you can choose to listen to one or both of the signals according to your needs. The former is more suitable for fast update of the UI, while the latter provides greater flexibility, but requires additional processing steps.

6、void QWebEngineView::loadFinished(bool ok)

void QWebEngineView::loadFinished(bool ok)It is a signal of the QWebEngineView class in the Qt WebEngine module. When the web page is loaded, the signal will be triggered regardless of whether it is loaded successfully or not.

Parametersbool okIndicates whether the loading operation is successful. ifokfortrue, it means that the web page loading is completed smoothly; iffalse, it means an error or interrupt was encountered during loading.

Developers usually connect to this signal to perform subsequent operations after the web page is loaded, for example:

QObject::connect(webView, &amp;QWebEngineView::loadFinished, [=](bool success){
    if (success) {
        qDebug() &lt;&lt; "Web page loaded successfully.";
        // Execute operations after successful loading, such as hiding progress bars, enabling UI elements, etc.    } else {
        qDebug() &lt;&lt; "Failed to load web page!";
        // Execute operations after loading failure, such as displaying error messages, attempting to reload, etc.    }
});

This signal is very important because it can help developers track the status of web page loading and execute corresponding program logic based on the loading results.

7、void QWebEngineView::loadProgress(int progress)

void QWebEngineView::loadProgress(int progress)It is a signal of the QWebEngineView class in the Qt WebEngine module. When the web page is loaded, this signal will be periodically transmitted to inform the current loading percentage of progress.

Parametersint progressIt is an integer between 0 and 100, representing the progress of the web page loading. 0 means that the load has not started or has just begun, and 100 means that the load has been completed.

Developers can connect to this signal to display the progress of web page loading in real time, for example, reflected on the progress bar

QObject::connect(webView, &amp;QWebEngineView::loadProgress, [=](int currentProgress){
    progressBar-&gt;setValue(currentProgress);
    // Here the progressBar is a QProgressBar object used to display the loading progress});

In this way, whenever the progress of the web page loading changes, the progress bar will update its value accordingly, allowing users to intuitively understand the loading process.

8、void QWebEngineView::loadStarted()

void QWebEngineView::loadStarted()It is a signal of the QWebEngineView class in the Qt WebEngine module. When the QWebEngineView starts loading a web page, the signal is immediately triggered.

Developers usually connect to this signal to perform some operations at the beginning of web page loading, such as displaying loading animations, disabling certain interactive functions, etc., to indicate that the web page is loading. Here is a simple example:

QObject::connect(webView, &amp;QWebEngineView::loadStarted, [=](){
    // Show loading progress bar or loading animation    loadingIndicator-&gt;start();
    // Some interactions between users and the interface are prohibited    someInteractiveWidget-&gt;setEnabled(false);
    qDebug() &lt;&lt; "Web page loading started...";
});

In this code, when the web page loading starts, the loadingIndicator is started, and a certain interactive widget is disabled to prevent the user from performing invalid operations during loading. At the same time, the console will print a message that the loading has started.

9、void QWebEngineView::reload()

void QWebEngineView::reload()It is in the Qt WebEngine moduleQWebEngineViewA member function of the class. Calling this function will cause the currentQWebEngineViewThe web page loaded in the view is reloaded. This means it terminates the loading of the current page (if it is still loading) and refetches the latest version of the page from the server.

In practical applications, this method may be used when you need to update the web page content or process the web page refresh logic. For example, when a user clicks the refresh button or the program needs to ensure that the latest web page data is displayed, you can callreload()Functions to implement page refresh.

Here is a basic example of calling the function:

QWebEngineView *webView = new QWebEngineView(parent);
// ... Perform views initialization and loading URLs and other operations...// When the page needs to be refreshedwebView-&gt;reload();

10、void QWebEngineView::renderProcessTerminated(QWebEnginePage::RenderProcessTerminationStatus terminationStatus, int exitCode)

void QWebEngineView::renderProcessTerminated(QWebEnginePage::RenderProcessTerminationStatus terminationStatus, int exitCode)It is a signal of the QWebEngineView class in the Qt WebEngine module. This signal will be triggered when the web rendering process suddenly terminates.

Parameter description:

  • QWebEnginePage::RenderProcessTerminationStatus terminationStatus: indicates the state at which the rendering process ends. It can be various situations such as normal exit, abnormal exit, forced ending by the browser, etc.
  • int exitCode: Indicates the exit code of the rendering process. For abnormal exits, etc., this code helps to understand the specific reasons why the process terminates.

When this signal is received, developers usually need to deal with this situation, such as reloading the web page, displaying error messages, or recording logs. For example:

QObject::connect(webView, &amp;QWebEngineView::renderProcessTerminated, [&amp;](QWebEnginePage::RenderProcessTerminationStatus status, int code){
    switch (status) {
    case QWebEnginePage::NormalTerminationStatus:
        qDebug() &lt;&lt; "Render process terminated normally with exit code:" &lt;&lt; code;
        // May handle the logic of normal ending        break;
    case QWebEnginePage::AbnormalTerminationStatus:
        qDebug() &lt;&lt; "Render process terminated abnormally with exit code:" &lt;&lt; code;
        // Reload the page or other recovery measures may be required        webView-&gt;reload();
        break;
    case QWebEnginePage::CrashedStatus:
        qDebug() &lt;&lt; "Render process crashed with exit code:" &lt;&lt; code;
        // Error message may be displayed or other error handling strategies may be adopted        QMessageBox::critical(nullptr, "Error", "The render process has crashed.");
        break;
    default:
        // Handling of other unknown situations        break;
    }
});

11、void QWebEngineView::selectionChanged()

void QWebEngineView::selectionChanged()It is a signal of the QWebEngineView class in the Qt WebEngine module. This signal is triggered when the user changes text selection in a web page (for example, highlighting text) .

When you connect to this signal, you can write the corresponding slot function to receive notifications and perform corresponding operations accordingly, such as obtaining the currently selected text, copying it to the clipboard, or doing other text processing work. Here is a basic example:

QObject::connect(webView, &amp;QWebEngineView::selectionChanged, [=]() {
    QString selectedText = webView-&gt;selectedText();
    qDebug() &lt;&lt; "Selected text changed to: " &lt;&lt; selectedText;
    // Here you can handle changes in selected text, such as displaying to another control, saving to the clipboard, etc.});

When the text selection in the web page changes, the above code captures this event and prints out the currently selected text.

12、void QWebEngineView::stop()

void QWebEngineView::stop()It is a member function of the QWebEngineView class in the Qt WebEngine module. When this function is called, it stops the web page currently loading or rendering. That is to say, if the QWebEngineView is loading a web page, or performing JavaScript scripts, playing media, etc., calling this function will abort these activities.

In practical applications, this function is often used when users cancel loading or need to end the loading task in advance when encountering network problems. For example, when the user presses the "Stop Loading" button:

QPushButton *stopButton = new QPushButton("Stop Loading", this);
QObject::connect(stopButton, &QPushButton::clicked, webView, &QWebEngineView::stop);

13、void QWebEngineView::titleChanged(const QString &title)

void QWebEngineView::titleChanged(const QString &title)It is a signal of the QWebEngineView class in the Qt WebEngine module. When the web page title changes, the signal will be triggered. ParameterstitleContains a new web page title string.

In web application development, developers usually connect to this signal to update the title bar or label in the application interface to reflect the actual title of the current web page. For example:

QObject::connect(webView, &amp;QWebEngineView::titleChanged, [=](const QString &amp;newTitle){
    // Update window title bar or custom title display control    windowTitleBar-&gt;setText(newTitle);
    // or    this-&gt;setWindowTitle(newTitle);
});

In this example, when the web page title changes, the window title bar (windowTitleBar) or the title of the entire window will be updated to the new page title.

14、void QWebEngineView::urlChanged(const QUrl &url)

void QWebEngineView::urlChanged(const QUrl &url)It is a signal of the QWebEngineView class in the Qt WebEngine module. When the URL of the web page in the QWebEngineView changes (for example, the user clicks on the link and jumps to a new web page, or changes through JavaScript), the signal is triggered.

Signal parametersconst QUrl &urlPoints to the new URL address currently loading on the web page. Developers usually connect to this signal to update relevant UI elements, such as address bars, or track users' navigation history, or even restrict users from accessing pre-approved series of URLs, etc.

Here is a simple example showing how to update the address bar when the URL changes:

QObject::connect(webView, &amp;QWebEngineView::urlChanged, [=](const QUrl &amp;newUrl){
    addressLineEdit-&gt;setText(()); // Assume addressLineEdit is a lineEdit control that displays the current URL});

The above code will be updated when the webpage URL in QWebEngineView changesaddressLineEditThe text content of the control is the new URL.

15、QWebEngineView::~QWebEngineView()

QWebEngineView::~QWebEngineView()It is the destructor of the QWebEngineView class in the Qt WebEngine module. When the lifetime of a QWebEngineView object ends, the system will automatically call this destructor to clean up and release the resources occupied by the object.

The main functions of the destructor are:

  • Clean up all resources related to QWebEngineView, such as closing the associated network request, freeing memory, disconnecting signal slot relationships, etc.
  • The destructor inherited from QObject also automatically logs out the object to avoid memory leaks or hanging pointers.

Normally, programmers do not need to explicitly call destructors, but are automatically called by C++'s automatic memory management system when objects are out of scope or are deleted by smart pointers. However, in some cases where memory is required, such as when creating a QWebEngineView object on the heap, the delete operator should be called when the object is no longer needed, which triggers the destructor to perform cleaning work.

16、void QWebEngineView::closeEvent(QCloseEvent *event)

void QWebEngineView::closeEvent(QCloseEvent *event)It is a virtual function in the Qt framework that covers the base class QWidget. When the QWebEngineView window receives a close event (for example, the user clicks the window close button or the program calls the close() function), the function will be called.

Rewriting this function in QWebEngineView gives you the opportunity to perform specific operations before the window is closed, such as saving the current state, cleaning up resources, confirming whether the user really wants to close, etc. Here is a simple example:

void MyWebEngineView::closeEvent(QCloseEvent *event)
{
    // If you need to confirm whether the user really wants to close the window, you can pop up a dialog box to ask    if (maybeSaveOrCancel()) {
        // The user agrees to close and accepts the closure event        event-&gt;accept();
    } else {
        // The user does not agree to the closure and refuses to close the event        event-&gt;ignore();
    }

    // You can also perform other necessary cleaning operations before closing the window    // ...

    // If this function is not overridden, the window will be closed directly when the closing event is received.    // By overwriting this function, we can control the shutdown process}

In this example,MyWebEngineViewIt is an inherited fromQWebEngineViewcustom class, it rewrittencloseEventfunction. Inside the function, the behavior of closing events can be handled as needed.

17、void QWebEngineView::contextMenuEvent(QContextMenuEvent *event)

void QWebEngineView::contextMenuEvent(QContextMenuEvent *event)It is an overloaded event handling function of the QWebEngineView class in the Qt WebEngine module. When the user right-clicks the mouse in the QWebEngineView control, a context menu event will be triggered, and this function will be called.

Within this function, developers can customize the behavior of context menus, such as displaying custom menu items, or preventing the default context menu from appearing. Here is a simple example:

void MyWebEngineView::contextMenuEvent(QContextMenuEvent *event)
{
    QMenu contextMenu(this);

    // Add custom menu items    QAction *copyAction = (tr("&amp;Copy"));
    connect(copyAction, &amp;QAction::triggered, this, &amp;MyWebEngineView::copySelection);

    // Show custom context menu    (event-&gt;globalPos());

    // Prevent the default context menu from displaying    event-&gt;accept();
}

// Define a slot function to handle copy operationsvoid MyWebEngineView::copySelection()
{
    // Get and copy the currently selected text    QString selection = this-&gt;selectedText();
    qApp-&gt;clipboard()-&gt;setText(selection);
}

In the above code, when the user right-clicks in the QWebEngineView, a custom context menu pops up, including a "Copy" option. If the user clicks "Copy", it will be calledcopySelectionSlot function, copy the currently selected text to the clipboard. At the same time, callevent->accept()to prevent the default context menu from appearing.

18、QWebEngineView *QWebEngineView::createWindow(QWebEnginePage::WebWindowType type)

QWebEngineView *QWebEngineView::createWindow(QWebEnginePage::WebWindowType type)It is a virtual member function of the QWebEngineView class in the Qt WebEngine module. When an event that needs to open a new window is triggered inside the webpage (for example, clicking on a<a target="_blank">This function will be called when a tag or JavaScript code running that opens a new window.

This function receives an enumeration parameterQWebEnginePage::WebWindowType type, This parameter identifies the type of new window, such as new tab page, pop-up window, etc.

The developer needs to rewrite this function to create and return a new QWebEngineView instance to handle the opening and display of a new window. If this function is not overridden, a new window may not be created or displayed incorrectly by default.

Sample code:

class CustomWebEngineView : public QWebEngineView
{
    Q_OBJECT
public:
    CustomWebEngineView(QWidget *parent = nullptr) : QWebEngineView(parent) {}

protected:
    virtual QWebEngineView *createWindow(QWebEnginePage::WebWindowType type) override
    {
        // Create and return a new QWebEngineView instance        auto newView = new QWebEngineView(parentWidget());
        // The appearance or behavior of a new window can be adjusted according to the type        // ...
        return newView;
    }
};

In the above example, whenever an open new window event is triggered inside the web page,createWindowThe function will be called and returns a new QWebEngineView instance. Developers can customize the behavior and style of a new window based on the window type, such as embedding it into an existing window, or displaying it as a new window.

19、void QWebEngineView::dragEnterEvent(QDragEnterEvent *e)

void QWebEngineView::dragEnterEvent(QDragEnterEvent *e)It is an overloaded event handling function of the QWebEngineView class in the Qt WebEngine module. When the mouse cursor in the drag-and-drop operation enters the QWebEngineView control area, the dragEnterEvent event is triggered.

This function allows you to customize the behavior when dragging data into QWebEngineView, such as deciding whether to accept this drag and drop operation. In the function, you can check the drag-and-drop data type and set the event's acceptProposedAction() property to decide whether to allow data to be dropped on this control.

void MyWebEngineView::dragEnterEvent(QDragEnterEvent *e)
{
    if (e-&gt;mimeData()-&gt;hasFormat("text/plain")) // Check whether the dragged data is in plain text format    {
        e-&gt;acceptProposedAction(); // Accept this drag and drop operation to allow data to be dropped on this control    }
    else
    {
        e-&gt;ignore(); // This drag and drop operation is not accepted    }
}

In this example, if the dragged data type is plain text, we allow drag and drop to QWebEngineView; otherwise, ignore this drag and drop event. In actual applications, you may need to process different types of drag and drop data according to your application needs.

20、void QWebEngineView::dragLeaveEvent(QDragLeaveEvent *e)

void QWebEngineView::dragLeaveEvent(QDragLeaveEvent *e)It is an overloaded event handling function of the QWebEngineView class in the Qt WebEngine module. When the mouse cursor in the drag-and-drop operation leaves the QWebEngineView control area, the dragLeaveEvent event is triggered.

This function is mainly used to handle the situation where the mouse leaves the view area during drag and drop operation. Usually, when customizing the drag and drop function, it can be cancelled in this function.dragEnterEventordragMoveEventsome visual effects or states set in.

Sample code:

void MyWebEngineView::dragLeaveEvent(QDragLeaveEvent *e)
{
    // Here you can clear any temporary state or visual effects that were previously set in dragEnterEvent or dragMoveEvent    // For example, if the background color is changed when the mouse enters, the original background color can be restored at this time    setBackgroundColor(originalBackgroundColor);

    // By default, the event is accepted    e-&gt;accept();
}

In the above code, when the drag operation leaves the view, the view returns to its original background color. In fact, the specific processing logic depends on your application requirements and the customization of drag and drop events before.

21、void QWebEngineView::dragMoveEvent(QDragMoveEvent *e)

void QWebEngineView::dragMoveEvent(QDragMoveEvent *e)It is an overloaded event handling function of the QWebEngineView class in the Qt WebEngine module. When the mouse in the drag-and-drop operation moves within the QWebEngineView control area, the dragMoveEvent event is triggered.

This function is mainly used to handle the interactive behavior of the mouse when moving during dragging and dropping. For example, it can detect the current position of the mouse, decide whether to allow dragging and dropping the target area, and update relevant feedback information, such as changing the shape of the mouse, updating prompt information, etc.

Sample code:

void MyWebEngineView::dragMoveEvent(QDragMoveEvent *e)
{
    // Check whether the current drag and drop location meets the conditions, for example within an acceptable range    if (isDropAllowed(e-&gt;pos()))
    {
        // If data is allowed to be dropped, the drag event is accepted        e-&gt;acceptProposedAction();
        // You can update the interface status here, such as changing the background color of the control, displaying prompts for the upcoming placement, etc.    }
    else
    {
        // Otherwise, the drag event is rejected        e-&gt;ignore();
    }
}

// Sample helper function to check whether the drag and drop position meets the conditionsbool MyWebEngineView::isDropAllowed(const QPoint &amp;pos)
{
    // Here you can determine whether the pos coordinate is within the valid range based on actual needs    // The following code is only an example, and the actual logic needs to be written according to the specific application scenario    QRect rect = this-&gt;rect();
    return (pos);
}

In the above code, when the drag operation moves within the QWebEngineView, it will check whether the current position meets the condition for putting data. If it is satisfied, the drag event will be accepted, otherwise it will be ignored. At the same time, more complex drag and drop logic can be implemented in this function according to actual conditions.

22、void QWebEngineView::dropEvent(QDropEvent *e)

void QWebEngineView::dropEvent(QDropEvent *e)It is an overloaded event handling function of the QWebEngineView class in the Qt WebEngine module. When the user completes a drag and drop operation (i.e., releases the mouse button) on the QWebEngineView control, the dropEvent event is triggered.

In this function, you can handle the actual data exchange of drag and drop, get the data type of drag and drop, and apply the data to the QWebEngineView, such as inserting text, pictures, or other types of data into a web page.

Here is a simple example:

void MyWebEngineView::dropEvent(QDropEvent *e)
{
    if (e-&gt;mimeData()-&gt;hasUrls())
    {
        foreach (const QUrl &amp;url, e-&gt;mimeData()-&gt;urls())
        {
            // Process URL data, such as loading drag and drop links            load(url);
        }
        e-&gt;acceptProposedAction();
    }
    else if (e-&gt;mimeData()-&gt;hasText())
    {
        // Process text data, such as inserting drag and drop text into a web page        QString text = e-&gt;mimeData()-&gt;text();
        // Here, there is a function of insertTextToWebPage(text) that can insert text into a web page        insertTextToWebPage(text);
        e-&gt;acceptProposedAction();
    }
    else
    {
        e-&gt;ignore();
    }
}

In this example, when the user completes the drag-and-drop operation on the QWebEngineView, the program checks the drag-and-drop data type. If it is a URL link, the link is loaded; if it is text, it is inserted into the web page. If the data type is not supported, this drag and drop event is ignored.

23、bool QWebEngineView::event(QEvent *ev)

bool QWebEngineView::event(QEvent *ev)is an overloaded function of the QWebEngineView class in the Qt framework. In Qt, all classes inherited from QObject can handle various events by overwriting the event() function. This function takes a QEvent pointer as a parameter, checks the event type and handles it appropriately.

In QWebEngineView, the event() function can handle all events sent to QWebEngineView objects, including but not limited to keyboard input, mouse events, window events, etc. If you want to customize the behavior of the QWebEngineView, such as handling some special events or extending the default behavior, you can override this function.

Here is a simple example showing how to handle a specific type of event in the event() function:

bool MyWebEngineView::event(QEvent *ev)
{
    if (ev-&gt;type() == QEvent::KeyPress) {
        QKeyEvent *keyEvent = static_cast&lt;QKeyEvent*&gt;(ev);
        // Handle key events, such as disabling the function of a key        if (keyEvent-&gt;key() == Qt::Key_F5) {
            // F5 key is prohibited from refreshing the page            ev-&gt;ignore();
            return true;
        }
    }

    // For unhandled events, call the event() function of the parent class    return QWebEngineView::event(ev);
}

In the above code, when the QWebEngineView receives a key press event, it will check whether it is the F5 key. If so, the event will be ignored (the default refresh page operation is not performed), and true means that the event has been processed. For other types of events, if there is no special processing, it will be handed over to the base class of QWebEngineView.

24、void QWebEngineView::findText(const QString &subString, QWebEnginePage::FindFlags options = QWebEnginePage::FindFlags(), const QWebEngineCallback<bool> &resultCallback = QWebEngineCallback<bool>())

void QWebEngineView::findText(const QString &subString, QWebEnginePage::FindFlags options = QWebEnginePage::FindFlags(), const QWebEngineCallback<bool> &resultCallback = QWebEngineCallback<bool>())It is a member function of the QWebEngineView class in the Qt WebEngine module, which is used to find the specified string in the content of the web page.

Function parameter explanation:

  • const QString &subString: A string to search for in a web page.

  • QWebEnginePage::FindFlags options: Find options, which can be a combination of the following flags (using | symbol connection):

    • QWebEnginePage::CaseSensitively: case sensitive search.
    • QWebEnginePage::HighlightAllOccurrences: Highlight all found results.
    • QWebEnginePage::WordStart: Look up from the beginning of the word.
    • Other possible search options.
  • const QWebEngineCallback<bool> &resultCallback: The search result callback function. When the search is completed, this callback function will be called and a Boolean value is passed to indicate whether a match has been found.

("Search keywords", QWebEnginePage::FindFlags(QWebEnginePage::CaseSensitively | QWebEnginePage::HighlightAllOccurrences),
                       [](bool found) {
                           if (found) {
                               qDebug() &lt;&lt; "Match found";
                           } else {
                               qDebug() &lt;&lt; "No match found";
                           }
                       });

In the above code, we try to find "Search Keyword" in the web page, while setting the lookup option to case sensitive and highlight all matches. When the search operation is completed, the provided lambda expression will be called as the callback function and the search result will be output.

25、void QWebEngineView::hideEvent(QHideEvent *event)

void QWebEngineView::hideEvent(QHideEvent *event)It is an overloaded event handling function of the QWebEngineView class in the Qt framework. This function is called when the QWebEngineView control becomes invisible (for example, the window is minimized or hidden).

In practical applications, rewriting this function allows you to perform specific operations when the control is hidden, such as pausing video playback, freeing resources to save memory, recording user behavior, etc. The sample code is as follows:

void MyWebEngineView::hideEvent(QHideEvent *event)
{
    // Stop video playback or other operations that consume a lot of resources    if (())
        ();

    // Record the time point or other related information of the user's hidden window    logUserAction("Web view hidden");

    // Call the hideEvent method of the parent class to ensure that the default hidden event processing of Qt can also be executed    QWebEngineView::hideEvent(event);
}

In this example, when the QWebEngineView is hidden, the video playback will first be checked and stopped (assuming herevideoPlayeris a video player object), and then record the user's hidden actions. Finally, call the parent class QWebEngineViewhideEventMethod to execute the default event processing logic.

26、QWebEngineHistory *QWebEngineView::history() const

QWebEngineHistory *QWebEngineView::history() constIt is a member function of the QWebEngineView class in the Qt WebEngine module. This function returns a pointer to the QWebEngineHistory object that provides access to the current QWebEngineView browsing history.

The QWebEngineHistory class provides many methods to manipulate browsing history, such as:

  • int count(): Returns the total number of items in the history.
  • QUrl urlAt(int index): Returns the historical item URL at the specified index.
  • int currentIndex(): Returns the index of the currently activated page in the history.
  • void back(): Load the previous page in the history.
  • void forward(): Load the next page in the history.
  • void clear(): Clear browsing history.

By callingQWebEngineView::history()Functions, developers can obtain the browsing history of QWebEngineView and operate as needed, such as implementing forward and back functions, or traversing the history to perform other operations.

27、void QWebEngineView::load(const QUrl &url)

void QWebEngineView::load(const QUrl &url)It is a member function of the QWebEngineView class in the Qt WebEngine module. This function is used to load the specified URL address in the QWebEngineView control, that is, open and display the content of the specified web page in the view.

Example of usage:

#include &lt;QApplication&gt;
#include &lt;QWebEngineView&gt;
#include &lt;QUrl&gt;

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    QWebEngineView webView;
    ();

    // Load a URL    QUrl url("");
    (url);

    return ();
}

In this example, we create a QWebEngineView object and make it visible. Next, we define a QUrl object, point to "", and then call `(url)` to load and display the web page. After calling this function, the QWebEngineView will start loading the specified web page and display its contents after the loading is completed.

28、void QWebEngineView::load(const QWebEngineHttpRequest &request)

void QWebEngineView::load(const QWebEngineHttpRequest &request)It is a member function of the QWebEngineView class in the Qt WebEngine module. Unlike loading web pages only through URLs, this function allows you to load web page content through a detailed HTTP request object.

Using this function, you can control the requests sent to the server in more detail, such as setting up HTTP methods (GET, POST, etc.), adding HTTP headers, transmitting data bodies, etc.

Sample code:

QWebEngineHttpRequest request;
(QUrl("/api/data"));
(QWebEngineHttpRequest::Post); // Set the HTTP method to POST(QNetworkRequest::ContentTypeHeader, "application/json"); // Set Content-Type header
QJsonObject json;
("key", "value"); // Suppose we want to send JSON dataQJsonDocument doc(json);
((QJsonDocument::Compact)); // Set the request body to JSON data
(request); // Use customHTTPRequest to load data

In this example, we create a QWebEngineHttpRequest object and set the URL, HTTP method, Content-Type header, and request body. Then we pass this custom HTTP request object to(request)function to initiate an HTTP POST request with specific parameters. This is especially useful for web applications that require complex interactions with the server.

29、QWebEnginePage *QWebEngineView::page() const

QWebEnginePage *QWebEngineView::page() constIt is a member function of the QWebEngineView class in the Qt WebEngine module. This function returns a pointer to the QWebEnginePage object associated with the QWebEngineView.

The QWebEnginePage class provides a more detailed web page operation interface, such as obtaining web page content, executing JavaScript, handling web page loading events, managing web page cookies, printing web pages, etc. When you need to operate directly or get detailed information related to web pages in QWebEngineView view, you can use this function to get the QWebEnginePage object.

Example:

QWebEngineView *webView = new QWebEngineView(parent);
// Load the web page...QWebEnginePage *webPage = webView-&gt;page();

// More detailed web page operations can now be performed through the webPage objectwebPage-&gt;runJavaScript("('Hello from JavaScript');");

In the above example, we first create a QWebEngineView object and load the web page, and then call itpage()The function gets the associated QWebEnginePage object and executes a JavaScript command.

30、void QWebEngineView::load(const QWebEngineHttpRequest &request)

void QWebEngineView::load(const QWebEngineHttpRequest &request)It is a function of the QWebEngineView class in the Qt WebEngine module, which is used to load web page content based on the provided QWebEngineHttpRequest object. This function allows developers to customize HTTP requests, including setting request methods (such as GET, POST, etc.), request headers, and request bodies, so as to achieve more refined web page loading control.

For example, if you want to send JSON data to the server through the POST method and load the responding web page content, you can use this:

QWebEngineHttpRequest request;
(QUrl("/api/login")); // Set the requested URL(QWebEngineHttpRequest::Post); // Set the request method to POST
QJsonObject json;
json["username"] = "testuser";
json["password"] = "testpass";

QJsonDocument doc(json);
(QNetworkRequest::ContentTypeHeader, "application/json"); // Set Content-Type header(()); // Set the request body to JSON data
QWebEngineView *webView = new QWebEngineView(parentWidget);
webView-&gt;load(request); // Use customHTTPRequest to load the web page

In the above code, we create a QWebEngineHttpRequest object, set the URL, HTTP method, Content-Type header, and request body, and then pass the request object to the load function of the QWebEngineView to initiate a POST request to the specified URL and load the returned web page content.

31、QAction *QWebEngineView::pageAction(QWebEnginePage::WebAction action) const

QAction *QWebEngineView::pageAction(QWebEnginePage::WebAction action) constIt is a member function of the QWebEngineView class in the Qt WebEngine module. This function is used to get the QAction object associated with the given QWebEnginePage::WebAction.

QWebEnginePage::WebAction is an enumeration type that lists a series of actions related to web page operations, such as back, forward, refresh, stop loading, copying, pasting, etc. When you call this function and pass in a WebAction enumeration value, it returns a QAction object associated with the action.

With this QAction object, you can add it to a menu, toolbar, or associated shortcut keys, allowing users to perform these actions easily.

Example:

QAction *backAction = webView-&gt;pageAction(QWebEnginePage::WebAction::Back);
backAction-&gt;setShortcut(QKeySequence::Back); // Set the shortcut key of the back button to Alt+left direction keymenu-&gt;addAction(backAction); // Add back action to the menu

In the above example, we have obtained the QAction object associated with the back operation, set a shortcut key for it, and added it to the menu. In this way, the user can perform a back operation through menus or shortcut keys.

32、void QWebEngineView::setContent(const QByteArray &data, const QString &mimeType = QString(), const QUrl &baseUrl = QUrl())

void QWebEngineView::setContent(const QByteArray &data, const QString &mimeType = QString(), const QUrl &baseUrl = QUrl())It is a member function of the QWebEngineView class in the Qt WebEngine module. This function is used to load the given binary data into the QWebEngineView and display it as web page content.

Parameter explanation:

  • const QByteArray &data: Binary data containing the content of the web page to be displayed. This could be HTML, CSS, JavaScript, or other file content that matches some MIME type.
  • const QString &mimeType: Specify the MIME type of the data, such as "text/html", "image/jpeg", etc. If this parameter is omitted, the default is an empty string, usually in this case if the data looks like HTML, the WebKit engine will try to process it as HTML.
  • const QUrl &baseUrl: Specify the basic URL to parse relative URLs. If this parameter is omitted, the default is empty QUrl. When working with documents containing relative URLs, the underlying URL is very important because it affects the resolution of the resource loading path.

Example of usage:

QByteArray htmlData = "&lt;html&gt;&lt;body&gt;&lt;h1&gt;Hello, World!&lt;/h1&gt;&lt;/body&gt;&lt;/html&gt;";
QUrl base("");
webView-&gt;setContent(htmlData, "text/html", base);

The above code loads a piece of HTML data into the QWebEngineView and sets up a basic URL. In this way, if there are resources in the HTML document that reference relative paths (such as images, CSS files, etc.)

33、void QWebEngineView::setHtml(const QString &html, const QUrl &baseUrl = QUrl())

void QWebEngineView::setHtml(const QString &html, const QUrl &baseUrl = QUrl())is a function in the Qt WebEngine module, which is used toQWebEngineViewDisplay HTML content in the component. This function accepts two parameters:

const QString &html: This is the HTML content string you want to display.

const QUrl &baseUrl = QUrl(): This is the basic URL used to parse links and other resources for relative paths in HTML content. If omitted or left blank, the default base URL will be empty.

Example of usage:

QString htmlContent = "&lt;html&gt;&lt;body&gt;&lt;h1&gt;Hello, World!&lt;/h1&gt;&lt;/body&gt;&lt;/html&gt;";
QUrl baseUri(""); // You can leave blank to indicate that there is no basic URLmyWebEngineView-&gt;setHtml(htmlContent, baseUri);

In this code,myWebEngineViewIt's aQWebEngineViewObject of type, by callingsetHtmlFunctions, we can puthtmlContentThe HTML content in the string is displayed in this browser component, and the basic URL is specified as"". If there are links or reference resources with relative paths in HTML content, the engine will parse them using the provided underlying URL.

34、void QWebEngineView::setPage(QWebEnginePage *page)

A function of the QWebEngineView class, used to set the QWebEnginePage page object used by the QWebEngineView.

QWebEngineView is the main view component used to display web page content, while QWebEnginePage is the actual carrier that hosts web page content and web script execution environment. By callingsetPageFunction, you can assign a created QWebEnginePage object to the QWebEngineView, so that the view displays the content of the page.

For example:

QWebEnginePage *newPage = new QWebEnginePage(this);
// You can make further settings for newPage, such as setting page proxy, setting JavaScript permissions, etc.QWebEngineView *webView = new QWebEngineView(parent);
webView-&gt;setPage(newPage);
// Load the web pagenewPage-&gt;load(QUrl(""));

In this code, a new QWebEnginePage object is first creatednewPage, and then a QWebEngineView object is createdwebView, and passsetPageThe function willnewPageSet aswebViewThe page to be displayed is finally loaded with a URL tonewPageIn, thiswebViewThe content of this web page will be displayed.

35、QWebEngineSettings *QWebEngineView::settings() const

QWebEngineSettings *QWebEngineView::settings() constIt is a member function of the QWebEngineView class in the Qt WebEngine module. This function returns a pointer to a QWebEngineSettings object that contains various settings options related to the rendering and behavior of the web page associated with the QWebEngineView.

Through this function, you can obtain and modify various advanced settings of QWebEngineView, such as:

  • Is JavaScript enabled?
  • Whether to allow pop-up windows
  • Whether to load the picture
  • Whether to enable web plug-in
  • Whether to enable web page storage data (such as cookies, localStorage, etc.)
  • User Agent String Settings
  • Web security policies, etc.

Example:

QWebEngineView *webView = new QWebEngineView(parent);
QWebEngineSettings *settings = webView-&gt;settings();

//Picture loading is prohibitedsettings-&gt;setAttribute(QWebEngineSettings::AutoLoadImages, false);

// Allow JavaScript executionsettings-&gt;setAttribute(QWebEngineSettings::JavascriptEnabled, true);

In this example, we first get the settings object of the QWebEngineView, then respectively prohibit the automatic loading of the image, and enable JavaScript execution.

36、void QWebEngineView::showEvent(QShowEvent *event)

void QWebEngineView::showEvent(QShowEvent *event)is an override method of the QWebEngineView class in the Qt WebEngine module. It is a function that handles the showEvent event of QWidget. When the QWebEngineView component is about to become visible (i.e. from hidden to display), this event handler will be called.

Usually when rewriting this method, you can do some operations that need to be performed before or when the view is displayed, such as loading a web page, resizing the view, initializing the view state, etc. For example:

void MyWebEngineView::showEvent(QShowEvent *event)
{
    // Call the showEvent method of the parent class to ensure that the default processing is executed    QWebEngineView::showEvent(event);

    // Load an initial web page when view is displayed    load(QUrl(""));

    // Or perform other operations related to view display}

In this example, when MyWebEngineView becomes visible, it loads the specified web address. Of course, you can perform other customized operations in this function according to actual needs.

37、QSize QWebEngineView::sizeHint() const

QSize QWebEngineView::sizeHint() constis a member function of the QWebEngineView class in the Qt WebEngine module, which returns aQSizeObject, representing the optimal size hint recommended by the QWebEngineView component.

This size is usually calculated internally by QWebEngineView based on its content (such as the size of the loaded webpage) and is used to provide a reference size to the layout manager. The layout manager can better arrange the layout of components based on this prompt message, but the final size may differ from this size hint due to layout constraints or other factors.

In practice, if you want to get the ideal size of the QWebEngineView after its content is loaded, you can call this function to get it. However, the specific display size still needs to be determined by its parent window or layout manager.

38、void QWebEngineView::triggerPageAction(QWebEnginePage::WebAction action, bool checked = false)

void QWebEngineView::triggerPageAction(QWebEnginePage::WebAction action, bool checked = false)is a function of the QWebEngineView class in the Qt WebEngine module, which is used to trigger page operations associated with the given WebAction enumeration value.

QWebEnginePage::WebAction is an enumeration type that contains a variety of predefined web page operations, such as opening a new window, backing, forwarding, refreshing, stopping loading, printing, etc.

Function parameter description:

  • QWebEnginePage::WebAction action: Specify the WebAction operation to be triggered, for exampleQWebEnginePage::BackIndicates backwards,QWebEnginePage::ReloadIndicates refreshing the page, etc.
  • bool checked = false: For some operations, such as check/cancel check box (such as setting "Where to enable Java"), this parameter is used to specify the switch status of the operation. This parameter is not important for most WebActions, but may require setting for some operations involving state switching.

For example, trigger a page back operation:

webEngineView->triggerPageAction(QWebEnginePage::Back);

Trigger page refresh operation:

webEngineView->triggerPageAction(QWebEnginePage::Reload);

Summarize

This is the end of this article about QWebEngineView knowledge points of QT. For more QWebEngineView content related to QT, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!