How can I show data on QTableWidget and read data from it with header?
Asked
Active
Viewed 4.3k times
16
-
2@ayla Use Qt docs as start point: http://doc.trolltech.com/4.6/qtablewidget.html#details – mosg May 06 '10 at 07:58
-
What did you try, what docs did you read? Man 2010 must have been the salad days at SO for asking questions with zero effort. :) – eric Jul 12 '15 at 20:56
-
This [book on Qt](http://cartan.cas.suffolk.edu/oopdocbook/opensource/) is freely available and written by one of the best Qt trainers. You do need to understand something of the "Qt way" before just jumping in and clicking in the layout designer. – Martin Beckett May 06 '10 at 18:04
2 Answers
23
1). Create table with this example code:
filesTable = new QTableWidget(0, 2);
QStringList labels;
labels << tr("File Name") << tr("Size");
filesTable->setHorizontalHeaderLabels(labels);
filesTable->horizontalHeader()->setResizeMode(0, QHeaderView::Stretch);
filesTable->verticalHeader()->hide();
filesTable->setShowGrid(false);
2). Add row:
int row = filesTable->rowCount();
filesTable->insertRow(row);
filesTable->setItem(row, 0, fileNameItem);
filesTable->setItem(row, 1, sizeItem);
Enjoy.

mosg
- 12,041
- 12
- 65
- 87
-
2I think this line `filesTable->insertRow(row);` will override last row instead of adding a new one, it should be `filesTable->insertRow(row + 1);`. `fileNameItem` and `sizeItem` should be an instance of QTableWidgetItem like this: `QTableWidgetItem *fileNameItem = new QTableWidgetItem; fileNameItem->setText("file name item"); QTableWidgetItem *sizeItem = new QTableWidgetItem; sizeItem->setText("size item");` – SIFE Dec 06 '11 at 23:38
-
2@SIFE Thanks for the reply. I had checked you comment with my code and didn't find any problems. `insertRow( row )`, where `int row = filesTable->rowCount()` works correctly... – mosg Dec 07 '11 at 06:31
-
1Since the row count it is 0 based, using *row* is correct and using *row+1* is wrong but works due to some defensive "save the idiots" limits checking. :-) – Mr. Developerdude Jun 20 '16 at 02:12
6
To create columns:
ui->tableWidget->setColumnCount('the number of columns');
before you can insert rows you need to set the total rows:
ui->tableWidget->setRowCount('number of rows');
now loop through rows and columns and set the data in each
for (int ridx = 0 ; ridx < 'number of rows' ; ridx++ )
{
for (int cidx = 0 ; cidx < 'number of columns' ; cidx++)
{
QTableWidgetItem* item = new QTableWidgetItem();
item->setText('text or number to display');
ui->tableWidget->setItem(ridx,cidx,item);
}
}
to set the header
ui->tableWidget->setHorizontalHeaderLabels('QStringList containing the names');
hope it helps

LemonCool
- 1,240
- 10
- 18