我编写了一个快速测试来确定在创建和删除 a 时是否存在实际泄漏QQUickWidget
:
class Widget : public QWidget {
Q_OBJECT
public:
Widget(QWidget *parent = 0) : QWidget(parent) {
widget = 0;
count = 0;
resize(200, 200);
layout = new QVBoxLayout(this);
setLayout(layout);
QTimer * t = new QTimer(this);
t->setInterval(200);
t->setSingleShot(false);
t->start();
connect (t, SIGNAL(timeout()), this, SLOT(toggleQuickView()));
}
public slots:
void toggleQuickView() {
if (!widget) {
widget = new QQuickWidget;
widget->setSource(QUrl::fromLocalFile("d:\\main.qml"));
connect(widget, SIGNAL(destroyed()), this, SLOT(echo()));
layout->addWidget(widget);
} else {
layout->removeWidget(widget);
widget->deleteLater();
widget = 0;
}
}
void echo() {
PROCESS_MEMORY_COUNTERS memcount;
if (!GetProcessMemoryInfo(GetCurrentProcess(), &memcount, sizeof(memcount))) return;
qDebug() << ++count << "created and destroyed," << memcount.WorkingSetSize / (1024 * 1024) << "MB memory used";
}
private:
QVBoxLayout * layout;
QQuickWidget * widget;
int count;
};
它有一个计时器,可以创建/销毁QQuickWidget
内部已加载的 QML 文件,尽管结果最初会上升,但内存使用情况会及时稳定,这表明 Qt 代码中不太可能存在内存泄漏,如果你确实是内存泄漏,问题不在于Qt,而在于你自己的代码。
此外,值得一提的是,任务管理器实际上显示的进程使用的内存比 少GetProcessMemoryInfo()
,我认为后者是两者的更准确的衡量标准。任务管理器读数也没有表明任何内存泄漏,尽管它的值波动更大。
这是输出:
1 created and destroyed, 41 MB memory used
2 created and destroyed, 44 MB memory used
3 created and destroyed, 44 MB memory used
4 created and destroyed, 48 MB memory used
5 created and destroyed, 48 MB memory used
6 created and destroyed, 48 MB memory used
7 created and destroyed, 48 MB memory used
8 created and destroyed, 48 MB memory used
9 created and destroyed, 48 MB memory used
10 created and destroyed, 48 MB memory used
11 created and destroyed, 52 MB memory used
12 created and destroyed, 52 MB memory used
13 created and destroyed, 52 MB memory used
14 created and destroyed, 52 MB memory used
15 created and destroyed, 52 MB memory used
16 created and destroyed, 52 MB memory used
17 created and destroyed, 52 MB memory used
18 created and destroyed, 52 MB memory used
19 created and destroyed, 52 MB memory used
20 created and destroyed, 52 MB memory used
21 created and destroyed, 53 MB memory used
...
50 created and destroyed, 53 MB memory used
...
100 created and destroyed, 53 MB memory used
...
200 created and destroyed, 53 MB memory used
...
500 created and destroyed, 53 MB memory used