Overlay while loading page into QWebView

2019-07-22 13:02发布

问题:

Let's say we have a barebones QWebView:

#include <QApplication>
#include <QWebView>

int main(int argc, char** argv)
{
    QApplication app(argc, argv);
    QWebView view;

    view.show();
    view.setUrl(QUrl("http://google.com"));

    return app.exec();
}

How can I display a graphic overlay, preferably fullscreen with transparency and minimal animation (like timer/beachball/etc.) from when the page starts loading till it's finished? Should also be triggered when url changes from within the QWebView.

回答1:

You can use the LoadingOverlay class provided in this answer to draw an overlay over any QWidget. In your case, show the overlay on top of the QWebView when the signal loadStarted is triggered and hide it, when the signal loadFinished is triggered.

The following code should get you started. I put the code from the linked answer into overlay.h, the subclass of QWebView which handles the showing/hiding of the overlay is in webview.h:

webview.h

#include "overlay.h"
#include <QWebView>

class WebView : public QWebView
{
    Q_OBJECT
public:
    WebView(QWidget * parent) : QWebView(parent)
    {
        overlay = new LoadingOverlay(parent);
        connect(this,SIGNAL(loadFinished(bool)),this,SLOT(hideOverlay()));
        connect(this,SIGNAL(loadStarted()),this,SLOT(showOverlay())); 
    }
    ~WebView()
    {
    }

public slots:
    void showOverlay()
    {
        overlay->show();
    }

    void hideOverlay()
    {
        overlay->hide();
    }

private:
    LoadingOverlay* overlay;

};

main.cpp

#include <QApplication>

#include "overlay.h"
#include "webview.h"

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    ContainerWidget base;
    Webview w(&base);
    base.show();
    w.load(QUrl("http://google.com"));
    return a.exec();
}


标签: c++ qt qt5