我创建了一个自定义QWidget
(下面的代码)[内有QHBoxLayout
和两个QPushButtons
]并将其添加到GUI中的QVBoxLayout
。此自定义QWidget
- 对象将被多次创建和删除(代码如下)。
当我在控制台(嵌入式Linux)中输入top
时,每次添加新的QWidget
时都会增加RAM。没关系!但是在删除时我看不到内存减少。
我的代码出了什么问题?我想,删除自定义QWidgets
后RAM会减少。
myCustomWidget.h
class QCustomPushButton_withinIcon_LeftAndRight : public QWidget {
Q_OBJECT
public:
//functions
QCustomPushButton_withinIcon_LeftAndRight(QWidget *parent = 0);
~QCustomPushButton_withinIcon_LeftAndRight();
//other slots like:
// - virtual void mousePressEvent();
// - virtual void mouseReleaseEvent();
//other signals like:
// - void clicked();
//other functions like:
// - virtual void setEnabled(bool a);
// - virtual void paintEvent(QPaintEvent *);
// - ...
private:
//variables
QLayout *innerLayout; //!< Layout for two buttons
QPushButton *buttonLeft; //!< Button left
QPushButton *buttonRight; //!< Button right
//other variables like:
// - bool enabled;
// - ...
};
myCustomWidget.cpp
QCustomPushButton_withinIcon_LeftAndRight::QCustomPushButton_withinIcon_LeftAndRight(QWidget *parent) :
QWidget(parent),
mSVG (new svg),
mGradient (new gradient)
{
enabled = true;
//create innerLayout
innerLayout = new QHBoxLayout();
this->setLayout(innerLayout);
//create buttons
buttonLeft = new QPushButton();
buttonRight = new QPushButton();
innerLayout->addWidget(buttonLeft);
innerLayout->addWidget(buttonRight);
//create connections like:
// - connect (buttonLeft, SIGNAL(pressed()), this, SLOT(mousePressEvent()));
// - ...
//set some stylesheets
// - buttonLeft->setStyleSheet("...");
}
QCustomPushButton_withinIcon_LeftAndRight::~QCustomPushButton_withinIcon_LeftAndRight()
{
//I think, that this is right. If not, correct me.
delete buttonLeft;
delete buttonRight;
delete innerLayout;
}
//void QCustomPushButton_withinIcon_LeftAndRight::mousePressEvent() {}
//void QCustomPushButton_withinIcon_LeftAndRight::mouseReleaseEvent() {}
//void QCustomPushButton_withinIcon_LeftAndRight::setEnabled(bool a) {}
//void QCustomPushButton_withinIcon_LeftAndRight::paintEvent(QPaintEvent *) {} ...
gui.cpp(将QWidgets
添加到GUI中的QLayout
)
QCustomPushButton_withinIcon_LeftAndRight *button = new QCustomPushButton_withinIcon_LeftAndRight();
//add button to layout
parentUiWindow->aLayoutNameInGui->addWidget(button);
//aLayoutNameInGui is type of QVBoxLayout
gui.cpp(在GUI中的QWidgets
中删除QLayout
)
//delete all buttons in layout
QLayoutItem *child;
while((child = parentUiWindow->aLayoutNameInGui->layout()->takeAt(0)) != 0) {
//parentUiWindow->aLayoutNameInGui->removeWidget(child->widget()); //already removed by ->takeAt()
//child->widget()->setParent(NULL);
delete child->widget();
delete child;
}
答案 0 :(得分:1)
使用top
命令查看内存使用情况时,可能会出现误报。正如某些程序员dude 所述,当您在某些对象上调用delete
时,操作系统并不总是从您的进程中释放已分配的内存。
但是,您使用QCustomPushButton_withinIcon_LeftAndRight
在new
构造函数中创建了两个对象:
mSVG (new svg),
mGradient (new gradient)
但你似乎永远不会破坏这些物体。所以你可能会在那里发生内存泄漏。