Memory leak in QWebView

2019-07-25 00:27发布

问题:

I am using Qt5.4.3 and at some point, Qt prints out message like this

LEAK: 145 CachedResource
LEAK: 4432 WebCoreNode

I try to display a webpage on a Qt application, but whatever the webpage is, memory always leaks.

Here is the all code of project named"test"(I add the webview control in mainwindow.ui)

#test.pro
QT       += core gui webkit

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets webkitwidgets multimedia multimediawidgets

TARGET = EchartDemo
TEMPLATE = app


SOURCES += main.cpp\
        widget.cpp

HEADERS  += widget.h

FORMS    += widget.ui

INCLUDEPATH += $$PWD
MOC_DIR     = temp/moc
RCC_DIR     = temp/rcc
UI_DIR      = temp/ui
OBJECTS_DIR = temp/obj
DESTDIR     = bin

//main.cpp
#include "widget.h"
#include <QApplication>
#include <QTextCodec>

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

    Widget w;
    w.showMaximized();
    return a.exec();
}

//widget.h
#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>

namespace Ui {
class Widget;
}

class Widget : public QWidget
{
    Q_OBJECT

public:
    explicit Widget(QWidget *parent = 0);
    ~Widget();



private:
    Ui::Widget *ui;
};

#endif // WIDGET_H




//`widget.cpp`
#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
       ui->webView->load(QUrl("file:///"+qApp->applicationDirPath()+"/html/hao.html"));
}

Widget::~Widget()
{
    delete ui;
}

//hao.html
<meta http-equiv="Refresh" content="0; url=http://www.hao123.com/?1460255739"/><meta property="shurufa:url-navigate" content="985" />

In order to show the webpage normally, you should put the html file to the folder \build-EchartDemo-Desktop_Qt_5_4_2_MinGW_32bit-Debug\bin\html.

Of course, you can change the content of the hao.html file to whatever you like.

Why do I have these memory leaks?

回答1:

This is a known bug in Qt and these "memory leaks" are only warnings in some cases. You can read more about it here : Qt Bug 40373, and also see the other bug reports mentioning those leaks.

Also, you should consider to use QWebEngineView which is much better ;) (and update to Qt5.6, but it is another story!).