2

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.

p.i.g.
  • 2,815
  • 2
  • 24
  • 41
davidkomer
  • 3,020
  • 2
  • 23
  • 58

1 Answers1

2

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();
}
Community
  • 1
  • 1
m.s.
  • 16,063
  • 7
  • 53
  • 88
  • Wow, thank you! Since I'm coming from straight C into both Qt and C++ as new territory, this code sample is extremely helpful in also seeing just basic use of new syntax for me... will try it out and see how it goes before marking correct. Thanks! – davidkomer May 03 '15 at 21:04
  • Something I've noticed when using a `loadStarted` and `loadFinished` approach is that these signals can (and often are) called multiple times for the same webpage, as various frames load and finish loading. Some websites with very dynamic content are almost constantly in a "loading" state, so just keep this in mind when considering the UI/UX aspect of something like this :) – K. Barresi May 04 '15 at 04:19