C++ 如何向现有 QTableWidget 添加新行?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6957943/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to add new row to existing QTableWidget?
提问by icepopo
My app is phonebook(educational purposes). When user opens application, QTableWidged is filled with data loaded from .xml file. When user add new phone number, I would like to append this number to QTableWidget, but previously I setRowCount to current value, and now it is one row to little. How can I solve this problem?
我的应用程序是电话簿(教育目的)。当用户打开应用程序时,QTableWidged 会填充从 .xml 文件加载的数据。当用户添加新电话号码时,我想将此号码附加到 QTableWidget,但以前我将RowCount 设置为当前值,现在它是一行少了。我怎么解决这个问题?
回答by Chris
Doing something like this should work:
做这样的事情应该有效:
tableWidget->insertRow( tableWidget->rowCount() );
This will append a row to the end of your table. You can use the insertRow() function to insert new rows into the middle of your table as well.
这将在表格末尾追加一行。您也可以使用 insertRow() 函数将新行插入到表格的中间。
回答by DomTomCat
To extend @Chris' answer and provide additional information:
扩展@Chris 的回答并提供更多信息:
If you want to add data (i.e. push_back and fill a new row):
如果要添加数据(即 push_back 并填充新行):
tableWidget->insertRow ( tableWidget->rowCount() );
tableWidget->setItem ( tableWidget->rowCount()-1,
yourColumn,
new QTableWidgetItem(string));
// repeat for more columns
If you know the number of rows and columns in advance:
如果事先知道行数和列数:
ui->tableWidget->clear();
ui->tableWidget->setRowCount(numRows);
ui->tableWidget->setColumnCount(numColumns);
for (auto r=0; r<numRows; r++)
for (auto c=0; c<numColumns; c++)
tableWidget->setItem( r, c, new QTableWidgetItem(stringData(r,c)));