You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

QTableWidget调用setItem后无数据显示,已设置行列数

问题分析与解决
  • 问题根源:你创建的QTableWidgetItem是栈上的局部变量,for循环迭代结束后,该对象会被自动销毁。QTableWidget仅保存item的指针,当指针指向的内存被释放后,界面就无法显示数据。

  • 修复后的代码:

ui->MyQTableWidget->setRowCount(100);
ui->MyQTableWidget->setColumnCount(7);
QFile active(filepath);
if (!active.open(QIODevice::ReadOnly))
    return;
int line = 0;
QTextStream in(&active);
while(!in.atEnd()){
    QString Line = in.readLine();
    QStringList LinePart = Line.split(",", Qt::SkipEmptyParts);
    for(int j = 0; j < LinePart.size(); j++){
        // 改用new创建堆上的QTableWidgetItem,避免局部对象被销毁
        QTableWidgetItem *item = new QTableWidgetItem(LinePart.at(j));
        ui->MyQTableWidget->setItem(line, j, item);
    }
    line++;
}
  • 补充说明:Qt的QTableWidget会自动管理这些堆上创建的item内存,当表格销毁或调用clear()、setRowCount(0)等方法时,会自动删除这些item,无需手动释放,不会造成内存泄漏。

内容的提问来源于stack exchange,提问作者Drew Walton

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 17:50:12