[英]Do I have to delete these pointers?
這是我調用的MainWindow
類,並使用函數show()
使其對用戶可見。
class MainWindow : public QMainWindow
{
Q_OBJECT
QWidget *centralWidget;
QGridLayout* gridLayout;
QGridLayout* infoBoxLayout;
QHBoxLayout* buttonGroup;
QHBoxLayout* subCategoryLayout;
//... more widgets
public:
MainWindow(QWidget *parent = 0);
~MainWindow();
void setupUi();
void setupConnections();
private slots:
void add();
void edit();
void remove();
void find();
void clearAll();
void screenshotDesktop();
void screenshotApp();
void currentSubCategoryChanged( const QString& );
void curretCategoryChanged( const int );
void keyPressEvent( QKeyEvent * );
};
余為每個插件(宏后這些指針創建Q_OBJECT
)與所述堆的新對象new
。 但是,我沒有在程序中的任何地方刪除它們。 這會導致Qt內存泄漏嗎? 或者Qt中的某些東西在銷毀類時會自動刪除它們嗎?
如果窗口小部件具有父集,則Qt將處理刪除窗口小部件。 對於MainWindow,當你關閉它時,MainWindow及其子節點將被清理,所以將父節點傳遞給小部件的構造函數: -
QHBoxLayout* buttonGroup = new QHBoxLayout(this); // where this is the parent (MainWindow)
如果你創建一個像這樣的小部件: -
QHBoxLayout* buttonGroup = new QHBoxLayout;
並沒有通過父母,那么它將不會被清理,你將不得不自己處理。
如果將它們添加到gui層次結構中,則在刪除MainWindow
時將清除它們
這是因為父母對孩子的所有權(用gui的各種添加物設定)
所以this->add(centralWidget);
將調用centralWidget->setParent(this);
刪除MainWindow
會刪除centralWidget
你可以自己刪除QObjects,但要注意懸掛指針(QPointer會在這里提供幫助)。 雖然我建議使用deleteLater()
來確保當指針仍然存在於堆棧上時沒有奇怪的行為。
有關對象樹的更多信息,請參見此處
通過父子關系進行的自動內存管理由QObject
完成。 QWidget
恰好是一個QObject
,而且具有父窗口小部件的窗口小部件與父窗口具有相同的底層QObject。
帶子項的QObject會自動在析構函數中刪除其子項。
另一個對象可以采用QObject或QWidget。 例如,向布局添加窗口小部件會自動將它們重新顯示到設置布局的窗口小部件。 即使布局上還沒有設置窗口小部件,也會在將布局添加到窗口小部件(或具有窗口小部件集的布局)時完成重新顯示。 它非常聰明,可以節省大量的打字並減少錯誤的可能性。
將小部件添加到另一個小部件的慣用,最小化方式是:
MyWidget() {
QLayout * layout = new QHBoxLayout(this); // set a layout on this widget
layout->addWidget(new QLabel("foo")); // the label is reparented to this
layout->addWidget(new QPushButton("bar")); // the button is reparented to this
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.