2016-02-04 17 views
0

我想只有一個QToolBar實例,並在執行我的應用程序的過程中多次修改它。不過,我擔心Qt完成的內存管理。QToolBar兒童列表一直在增長。 Qt內存泄漏?

考慮以下幾點:

QToolBar toolBar; 
std::cout << toolBar.actions().size() << std::endl; // Prints 0 
toolBar.addSeparator(); // will add an action 
std::cout << toolBar.actions().size() << std::endl; // Prints 1 
toolBar.clear(); 
std::cout << toolBar.actions().size() << std::endl; // Prints 0 again. Good! 

最初的行動在QToolBar列表是空的。因此第一個cout打印「0」。內部操作通過「addSeparator」添加到該列表中。所以第二個cout打印「1」。最後,如預期的那樣,「清除」將刪除所有操作,最後一個cout再次打印「0」。

現在,考慮與「兒童名單」發生了什麼:

QToolBar toolBar; 
std::cout << toolBar.children().size() << std::endl; // Prints 3. Why? 
toolBar.addSeparator(); // will add an action 
std::cout << toolBar.children().size() << std::endl; // Prints 5. "addSeparator" has added two children. 
toolBar.clear(); 
std::cout << toolBar.children().size() << std::endl; // Still prints 5. "Clear" did not remove any children! 

最初,孩子們列表大小爲3。然後我稱之爲「addSeparator」和兩個傢伙被添加到列表中。好的,我可以忍受這一點。然而,在呼叫「清除」後,這些人不會被刪除。對於每個「addSeparator」或「addWidget」調用,添加兩個子項並且它們不會被刪除。

我使用Qt 5.4.1 for MSVC 2013,Windows。


編輯:添加peppe建議的代碼。請閱讀行註釋。

QToolBar toolBar; 
std::cout << toolBar.children().size() << std::endl; // Prints 3. 
toolBar.addSeparator(); 
std::cout << toolBar.children().size() << std::endl; // Prints 5. "addSeparator" has added two children. 

auto actions = toolBar.actions(); 

for (auto& a : actions) { 
    delete a; 
} 

std::cout << toolBar.children().size() << std::endl; // Now this prints 4. Shouldn't be 3? 

回答

2

只要看看在addSeparator實現:

QAction *QToolBar::addSeparator() 
{ 
    QAction *action = new QAction(this); 
    action->setSeparator(true); 
    addAction(action); 
    return action; 
} 

這將創建一個新的子QAction並將其添加到窗口小部件的操作列表。 clear清除動作列表,但不會破壞動作!因此,他們仍將作爲工具欄的孩子。

Qt並不知道你沒有在其他地方使用這些操作 - 它們意味着要在多個小部件中使用。如果要回收該內存,請刪除由addSeparator返回的操作。

+0

假設工具欄子項列表的大小爲x。然後我多次調用'toolBar.addSeparator()'。之後,我遍歷由'toolBar.actions()'返回的列表並刪除此列表中的每個指針。工具欄兒童列表的大小必須再次爲x?恐怕這沒有發生。 –

+0

你可以修改你的問題,顯示你通過它的代碼? – peppe

+0

完成。現在不是調用'toolBar.clear();'我遍歷動作列表並刪除每個動作。請閱讀行註釋。 –