QTableView is an interesting concept in QT. I was exploring it today and decided to post what I learnt from that.. I hope you will find it interesting/useful.
Download Source –>Download QTableView Source - Downloaded 4136 times
Create a new project and lets get started.. My folder structure is as below..
Open the forms->mainwindow.ui and insert a TableView into the form as below,
Now, open mainwindow.cpp, and drop the following code in the constructor,
QStandardItemModel *model = new QStandardItemModel(2,3,this); //2 Rows and 3 Columns model->setHorizontalHeaderItem(0, new QStandardItem(QString("Column1 Header"))); model->setHorizontalHeaderItem(1, new QStandardItem(QString("Column2 Header"))); model->setHorizontalHeaderItem(2, new QStandardItem(QString("Column3 Header"))); ui->tableView->setModel(model);
The code should go within your constructor as in the below image,
Run the program now, and you should get the below effect…
Now you have a QTableview with 3 columns and 2 rows with headers created.. We can add data to that section easily as below…
Add these code before the last line, and the table will fill the first col, first row with value..
QStandardItem *firstRow = new QStandardItem(QString("ColumnValue")); model->setItem(0,0,firstRow);
I have attached the source code for playing around.. Have fun.