Note that there are some explanatory texts on larger screens.

plurals
  1. POQt: Open links with target in default browser, without leaking memory
    text
    copied!<p>Searching through the Internet, I've come across so many ways, mostly nonfunctional, nonspecific, or partially functional, to do various things with <code>QWebView</code> and opening URLs.</p> <p>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 <code>WebViews</code> that aren't cleaned up until the process exits. How can I do this without leaking memory?</p> <p>Please forgive my rather sophomoric understanding of Qt in advance. I've only been using it for a handful of hours at this point.</p> <p>SSCCE:</p> <h3>test.hpp</h3> <pre><code>#include &lt;QMainWindow&gt; #include &lt;QWebView&gt; 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 &amp;request, NavigationType type); }; class WebView : public QWebView { Q_OBJECT public: QWebView* createWindow(QWebPage::WebWindowType type); }; </code></pre> <h3>test.cpp</h3> <pre><code>#include &lt;QApplication&gt; #include &lt;QGridLayout&gt; #include &lt;QNetworkRequest&gt; #include &lt;QDesktopServices&gt; #include "test.hpp" Window::Window() : QMainWindow() { m_web = new WebView; m_web-&gt;setHtml("&lt;div align=\"center\"&gt;&lt;a href=\"http://www.google.com/\"&gt;Same Window&lt;/a&gt; &lt;a href=\"http://www.google.com/\" target=\"_blank\"&gt;New Window&lt;/a&gt;&lt;/div&gt;"); setCentralWidget(m_web); } bool WebPage::acceptNavigationRequest(QWebFrame*, QNetworkRequest const&amp; request, NavigationType) { QDesktopServices::openUrl(request.url()); return false; } QWebView* WebView::createWindow(QWebPage::WebWindowType) { auto res = new WebView; auto page = new WebPage; res-&gt;setPage(page); return res; } int main(int argc, char *argv[]) { QApplication a(argc, argv); Window w; w.show(); return a.exec(); } </code></pre> <h3>test.pro</h3> <pre><code>QT += core gui network webkitwidgets widgets TEMPLATE = app TARGET = test INCLUDEPATH += . CONFIG += c++11 # Input SOURCES += test.cpp HEADERS += test.hpp </code></pre> <h3>To Compile and Run</h3> <pre><code>qmake test.pro make ./test </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload