我创建了一个自定义的QWidget
(下面的代码)[里面有一个QHBoxLayout
和两个QPushButtons
]并将它添加到一个QVBoxLayout
在 GUI 中。这个自定义 QWidget
对象将被创建和删除几次(下面的代码)。
当我在控制台(在嵌入式 Linux 上)中键入 top
时,每次添加新的 QWidget
时,RAM 都会增加。没关系!但是我看不到删除时 RAM 的减少。
我的代码有什么问题?我希望 RAM 在删除自定义 QWidgets
时减少。
我的自定义控件.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;
// - ...
};
我的自定义控件.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中QLayout
中的QWidgets
)
//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;
}
最佳答案
当您使用 top
命令查看内存使用情况时,您可能会得到误报。正如一些程序员所述,当您对某些对象调用delete
时,操作系统并不总是从您的进程中释放分配的内存。
但是,您正在使用 new
在 QCustomPushButton_withinIcon_LeftAndRight
构造函数中创建两个对象:
mSVG (new svg),
mGradient (new gradient)
但你似乎从来没有破坏过这些对象。所以你可能在那里有内存泄漏。
关于c++ - 在 QLayout 中创建和删除自定义 QWidgets 时出现 RAM 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45569987/