我已經創建了一個自定義QWidget
(代碼如下)[內部爲QHBoxLayout
和兩個QPushButtons
],並將它添加到GUI中的QVBoxLayout
。此自定義QWidget
對象將被創建並刪除多次(代碼如下)。在QLayout中創建和刪除自定義QWidgets時發生內存問題
當我輸入top
到控制檯(在嵌入式linux上)時,每增加一個新的QWidget
就會增加一個RAM。沒關係!但是我看不到刪除時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(在GUI添加QWidgets
到QLayout
)
QCustomPushButton_withinIcon_LeftAndRight *button = new QCustomPushButton_withinIcon_LeftAndRight();
//add button to layout
parentUiWindow->aLayoutNameInGui->addWidget(button);
//aLayoutNameInGui is type of QVBoxLayout
gui.cpp(刪除QWidgets
在GUI中的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;
}
我確信在這個問題上必須有一些重複。但是,「問題」很可能是操作系統在刪除或以其他方式釋放內存時不必從您的進程中取消映射分配的內存頁面。相反,它可以隨時做到這一點。這意味着這些頁面看起來像是內存泄漏。這是一個誤報。 –
如果將函數聲明放在代碼中而不是「gui.cpp(將QWidgets添加到GUI中的QLayout)」 –
我看到您創建了'mSVG'和'mGradient',它將更容易讀取和複製代碼'new',但是你會在任何地方摧毀這些物體嗎? – thuga