QWebView内存泄漏

Memory leak in QWebView

本文关键字:泄漏 内存 QWebView      更新时间:2023-10-16

我使用的是Qt5.4.3,在某个时刻,Qt打印出这样的消息

LEAK: 145 CachedResource
LEAK: 4432 WebCoreNode

我试图在Qt应用程序上显示一个网页,但无论网页是什么,内存总是会泄漏。

以下是名为"test"的项目的所有代码(我在mainwindow.ui中添加了webview控件)

#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" />

为了正常显示网页,您应该将html文件放在文件夹build-EchartDemo-Desktop_Qt_5_4_2_MinGW_32bit-Debugbinhtml中。

当然,您可以将hao.html文件的内容更改为任何您喜欢的内容。

为什么我有这些内存泄漏?

这是Qt中的一个已知错误,这些"内存泄漏"在某些情况下只是警告。你可以在这里阅读更多关于它的信息:Qt Bug 40373,也可以看到提到这些泄漏的其他错误报告。

此外,您应该考虑使用QWebEngineView,这要好得多;)(并更新到Qt5.6,但这是另一回事!)。