Searching through the Internet, I've come across so many ways, mostly nonfunctional, nonspecific, or partially functional, to do various things with QWebView
and opening URLs.
After much swearing and cursing, I've managed to get an example to do what I want, which is open normal links normally, and open anything that requests a new window in the external browser; however, there's a hitch. It leaks memory, because I make a bunch of extra WebViews
that aren't cleaned up until the process exits. How can I do this without leaking memory?
Please forgive my rather sophomoric understanding of Qt in advance. I've only been using it for a handful of hours at this point.
SSCCE:
test.hpp
#include <QMainWindow>
#include <QWebView>
class Window : public QMainWindow {
Q_OBJECT
public:
Window();
private:
QWebView* m_web;
private slots:
};
class WebPage : public QWebPage {
Q_OBJECT
public:
bool acceptNavigationRequest(QWebFrame *frame, const QNetworkRequest &request, NavigationType type);
};
class WebView : public QWebView {
Q_OBJECT
public:
QWebView* createWindow(QWebPage::WebWindowType type);
};
test.cpp
#include <QApplication>
#include <QGridLayout>
#include <QNetworkRequest>
#include <QDesktopServices>
#include "test.hpp"
Window::Window() :
QMainWindow() {
m_web = new WebView;
m_web->setHtml("<div align=\"center\"><a href=\"http://www.google.com/\">Same Window</a> <a href=\"http://www.google.com/\" target=\"_blank\">New Window</a></div>");
setCentralWidget(m_web);
}
bool WebPage::acceptNavigationRequest(QWebFrame*, QNetworkRequest const& request, NavigationType) {
QDesktopServices::openUrl(request.url());
return false;
}
QWebView* WebView::createWindow(QWebPage::WebWindowType) {
auto res = new WebView;
auto page = new WebPage;
res->setPage(page);
return res;
}
int main(int argc, char *argv[]) {
QApplication a(argc, argv);
Window w;
w.show();
return a.exec();
}
test.pro
QT += core gui network webkitwidgets widgets
TEMPLATE = app
TARGET = test
INCLUDEPATH += .
CONFIG += c++11
# Input
SOURCES += test.cpp
HEADERS += test.hpp
To Compile and Run
qmake test.pro
make
./test
QWebView
destructor and add some logging there, Or implement some memory leak debugging macros - both would tell you if destructor of ur class is actually called.m_web
is set as centralwidget - so it is indeed deleted when its parent dies. – Thionate