【问题标题】:QTableWidget update itemsQTableWidget 更新项目
【发布时间】:2012-12-31 16:02:25
【问题描述】:

我在更新 QTableWidgetItems 时遇到问题。我不明白我做错了什么:(

代码和解释。

一步一步的问题。

  1. 第一次插入 = OK,所有第一个单元格都已填充。
  2. 更新第一个插入的项目 = 好的,所有第一个单元格都已更新。
  3. 第二次插入 = OK,所有第二个单元格都被填充。
  4. 更新第二个插入的项目 = 好的,所有第二个单元格都已更新。
  5. 更新第一个插入的项目 = FAIL,所有第一个单元格都已更新,但 NEXT 单元格的第一个表为空。为什么?

代码:

void MainWindow::fillTable(QList<QByteArray> Info)
{
    int Row = ui->clientsList->rowCount() - 1; //Starts from 0.

    //Check if client row already exists.
    for(int i = Row; i >= 0; i--)
    {
        if(ui->clientsList->item(i, 0)->text().contains(QString(Info[1])))
        {
            //Update row.
            for(int u = 0; u < Info.count() - 1; u++)
            {
                ui->clientsList->setItem(i, u, new QTableWidgetItem(QString(Info[u + 1])));
            }

            return; //avoid new row insertion.
        }
    }

    //Insert new row.
    Row = ui->clientsList->rowCount() + 1;
    ui->clientsList->setRowCount(Row);
    for(int i = 0; i < Info.count() - 1; i++)
    {
        //Fill rows.
        ui->clientsList->setItem(Row - 1, i, new QTableWidgetItem(QString(Info[i + 1])));
    }
}

【问题讨论】:

  • 已修复,抱歉!虽然它也会被社区看到..

标签: c++ qt


【解决方案1】:

还没有完整的解决方案,但很少有 cmets:

1.可能存在内存泄漏

ui->clientsList->setItem(i, u, new QTableWidgetItem(QString(Info[u + 1])));

为什么不使用

 ui->clientsList->item(i, u)->setText(QString(Info[u + 1]));

这样更安全、更清晰。

2.我的理解是您依赖于 Info 的长度与行长度相同的事实,也许值得为此添加检查?

【讨论】:

  • 我的错! Info.count() 不仅仅是列,因此它给出了访问冲突。你的例子告诉我,谢谢! :D
  • 即使只将其放入更新行部分,而不是插入新行?如果是这样,你确定你的信息列表的长度总是一样的——也许它会不时变化,这就是你偶尔会有空单元格的原因吗?
猜你喜欢
  • 2015-01-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-11
相关资源
最近更新 更多