Qt 容器内存管理
我知道有很多关于Qt内存管理的问题。我还阅读了这些问题:
但就我而言,我又困惑了!
我有一个名为 myTable
的 QTableWidget
。我通过 setCellWidget
添加运行时小部件:
void MyClass::build()
{
for (int i=LOW; i<HIGH; i++)
{
QWidget *widget = new QWidget(myTable);
//
// ...
//
myTable->setCellWidget(i, 0, widget);
}
}
然后,我删除如下所示的所有项目:
void MyClass::destroy()
{
for (int i = myTable->rowCount(); i >= 0; --i)
myTable->removeRow(i);
}
这些方法在很长一段时间内调用多次。 myTable
作为这些小部件的父级将在程序的生命周期中存在。
方法 destroy()
会自动完全释放内存吗?或者我必须自己删除
分配的小部件,如下所示?
void MyClass::destroy2() // This maybe causes to crash !!
{
for (int i = myTable->rowCount(); i >= 0; --i)
{
QWidget *w = myTable->cellWidget(i, 0);
delete w;
myTable->removeRow(i);
}
}
I know there is many questions about memory management in Qt. Also I read these SO questions:
But in my case, I confused again!
I have a QTableWidget
with name myTable
. I add run-time widgets to it by setCellWidget
:
void MyClass::build()
{
for (int i=LOW; i<HIGH; i++)
{
QWidget *widget = new QWidget(myTable);
//
// ...
//
myTable->setCellWidget(i, 0, widget);
}
}
Then, I delete all items like below:
void MyClass::destroy()
{
for (int i = myTable->rowCount(); i >= 0; --i)
myTable->removeRow(i);
}
These methods call many times during long time. And myTable
as the parent of those widgets will live along program's life-time.
Dose method destroy()
release memory quite and automatically? Or I have to delete
allocated widgets myself like below?
void MyClass::destroy2() // This maybe causes to crash !!
{
for (int i = myTable->rowCount(); i >= 0; --i)
{
QWidget *w = myTable->cellWidget(i, 0);
delete w;
myTable->removeRow(i);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
一般来说,当对如何使用类有疑问或困惑时,请查阅该类应附带的文档。幸运的是,
QTableWidget::setCellWidget()
确实在事实附带文档:调用
myTable->setCellWidget()
后,该表现在拥有您传递给它的小部件。这意味着myTable
负责删除您传递给setCellWidget()
的小部件。删除行时,无需执行delete w;
操作。您的第一个destroy()
函数应该足够了。Generally speaking, when in doubt or confused about how to use a class, consult the documentation that should've came with it. Fortunately,
QTableWidget::setCellWidget()
does in fact come with documentation:After the call to
myTable->setCellWidget()
, the table now owns the widget you passed into it. That means thatmyTable
is responsible for deleting the widgets you pass tosetCellWidget()
. You don't need to dodelete w;
when you're removing rows. Your firstdestroy()
function should be sufficient.来自文档:
也就是说,您不需要手动清理,因为资源的释放会自动发生在 Qt 对象树中,您的
widget
已成为其中的一部分。From the documentation:
That is, you don't clean up manually, as freeing of resources happens automatically down the Qt object tree, of which your
widget
has become a part.