我希望只有一个 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”。最后,“clear”,正如预期的那样,删除所有操作,最后一个 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!
最初, child 列表的大小为 3。然后我调用“addSeparator”,两个人被添加到该列表中。好吧,我可以忍受。然而,在调用“清除”之后,这些家伙并没有被删除。对于每个“addSeparator”或“addWidget”调用,都会添加两个子项,并且永远不会删除它们。
我正在为 MSVC 2013、Windows 使用 Qt 5.4.1。
编辑:添加 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?
最佳答案
看看addSeparator
的实现:
QAction *QToolBar::addSeparator()
{
QAction *action = new QAction(this);
action->setSeparator(true);
addAction(action);
return action;
}
这将创建一个新的子 QAction
并将其添加到小部件的操作列表中。 clear
清除 Action 列表,但不破坏 Action !因此,它们仍将作为工具栏的子项存在。
Qt 不知道您没有在别处使用这些操作——它们旨在跨多个小部件使用。如果您想回收该内存,请删除 addSeparator
返回的操作。
关于c++ - QToolBar 子列表总是在增长。 Qt内存泄漏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35203411/