icepopo
icepopo

Reputation: 1637

How to add new row to existing QTableWidget?

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?

Upvotes: 32

Views: 89372

Answers (3)

Matheus Torquato
Matheus Torquato

Reputation: 1639

If you are using Python + PyQt5

from PyQt5 import QtCore, QtWidgets

# table is a QtWidgets.QTableWidget object
table.insertRow(table.rowCount()) 
item = QtWidgets.QTableWidgetItem(ITEM_CONTENT)
table.setItem(table.rowCount()-1, COLUMN_INDEX, item)
item = QtWidgets.QTableWidgetItem(ROW_LABEL_STRING)
table.setVerticalHeaderItem(table.rowCount()-1, item)

Upvotes: 5

DomTomCat
DomTomCat

Reputation: 8569

To extend @Chris' answer and provide additional information:

If you want to add data (i.e. push_back and fill a new row):

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)));

Upvotes: 29

Chris
Chris

Reputation: 17545

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.

Upvotes: 46

Related Questions