c++ - 容器的 Qt 内存管理

标签 c++ qt memory-management memory-leaks

我知道 Qt 中有很多关于内存管理的问题。我还阅读了这些 SO 问题:

但就我而言,我又糊涂了!

我有一个名为 myTableQTableWidget。我通过 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 作为这些小部件的父级将在程序的生命周期内存在。

Dose 方法 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);
    }
}

最佳答案

一般来说,当对如何使用一个类有疑问或困惑时,请查阅它应该附带的文档。还好,QTableWidget::setCellWidget() does in fact come with documentation :

void QTableWidget::setCellWidget ( int row, int column, QWidget * widget )

Sets the given widget to be displayed in the cell in the given row and column, passing the ownership of the widget to the table [emphasis mine]. If cell widget A is replaced with cell widget B, cell widget A will be deleted. For example, in the code snippet below, the QLineEdit object will be deleted.

    setCellWidget(index, new QLineEdit);
    ...
    setCellWidget(index, new QTextEdit);

调用 myTable->setCellWidget() 后,表格现在拥有您传递给它的小部件。这意味着 myTable 负责删除您传递给 setCellWidget() 的小部件。删除行时不需要执行 delete w;。您的第一个 destroy() 函数应该足够了。

关于c++ - 容器的 Qt 内存管理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9149621/

相关文章:

c++ - Boost MSM 开启当前状态

c++ - 在 Qt 虚拟键盘上实现 Backspace 和 Enter 键

qt - 在 QTableView 单元格的中心绘制 QPixmap

memory-management - Matlab:避免在 mex 中分配内存

c++ - 如何确定我的程序还剩多少虚拟内存?

c++ - OpenCV std::vector< cv::Point2f > 到 cv::Mat

c++ - Qt 反转选项卡 QTabWidget?

c++ - 单例析构函数

c++ - 构建一个形状类 Square

c++ - 我的 Qt QAbstractProxyModel 使用 ChartView 而不是使用 TableView 崩溃?