让我们说我有如下所示的QTableWidget:
__| columnname1 | columnname2
1 | name1 | value1
2 | name2 | value2
3 | name3 | value3
4 | name4 | value4
我用以下代码创建的:
ui->tableWidget->setColumnCount(2);
foreach(const QString& key, keys)
{
value = jsonObj.value(key);
ui->tableWidget->sortItems(int (1),Qt::DescendingOrder);
int currRow = ui->tableWidget->rowCount();
ui->tableWidget->setSortingEnabled(false);
ui->tableWidget->insertRow(ui->tableWidget->rowCount());
ui->tableWidget->setItem(currRow, 0, new QTableWidgetItem(key));
ui->tableWidget->setItem(currRow, 1, new QTableWidgetItem(value.toString()));
ui->tableWidget->setHorizontalHeaderLabels({"columnname1", "columnname2"});
ui->tableWidget->setSortingEnabled(true);
ui->tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);
}
例如,现在,我为name2设置了一个新值,如何替换name2所在的整行?
答案 0 :(得分:1)
首先,您要为每行调用一些函数,而整个表只需要调用一次。相反,您的代码示例应该看起来像这样:
@helpers/(.*)
然后,如果行'name2'具有新的 value ,则只需替换该值。您已经知道该怎么做:
ui->tableWidget->setColumnCount(2);
ui->tableWidget->setSortingEnabled(false);
ui->tableWidget->setHorizontalHeaderLabels({"columnname1", "columnname2"});
ui->tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);
foreach(const QString& key, keys)
{
value = jsonObj.value(key);
int currRow = ui->tableWidget->rowCount();
ui->tableWidget->insertRow(ui->tableWidget->rowCount());
ui->tableWidget->setItem(currRow, 0, new QTableWidgetItem(key));
ui->tableWidget->setItem(currRow, 1, new QTableWidgetItem(value.toString()));
}
ui->tableWidget->sortItems(int (1),Qt::DescendingOrder);
ui->tableWidget->setSortingEnabled(true);
我没有编译此示例代码,它可能有错别字或错误的函数名,但是您会明白的。