PDA

View Full Version : QTableView not working as expected.



junxuan
28th July 2009, 14:02
Hi guys, im rather new to Qt and im following a book : Foudations of Qt Development. Im trying to use the QTableView to display data, but it doesnt seem to work, it only displays a empty viewer.

This is my constructor:

MainDialog::MainDialog(QWidget *parent)
: QDialog(parent), ui(new Ui::MainDialog)
{
// ui->setupUi(this);
QTableView *table = new QTableView;

QStandardItemModel model(5, 2);
for (int row = 0; row < 5; ++row){
for (int col = 0; col < 2; ++col){
QStandardItem *item = new QStandardItem(QString("Row:%1, Column:%2").arg(row).arg(col));

if (col == 0){
for (int i = 0; i < 3; ++i){
item->appendRow(new QStandardItem( QString("Item %1").arg(i)));
}
}

model.setItem(row, col, item);
}
}

table->setModel(&model);
table->show();

QHBoxLayout *layout = new QHBoxLayout;
layout->addWidget(table);
setLayout(layout);
}

Please be forgiving with your words as im really new thanks:p

spirit
28th July 2009, 14:11
you creates QStandardItemModel model(5, 2); in a stack (an object will be destroyed when out of scope). you should create in the heap, i.e. QStandardItemModel *model = new QStandardItemModel(5, 2);.

junxuan
28th July 2009, 14:18
ahh ty, cause the book used it in the main function. Thanks for your expertise:)

junxuan
29th July 2009, 08:25
After successfully implementing the QTableView, how do i make it stretch fully? As there are gaps on the right and bottom.

junxuan
29th July 2009, 10:50
im not sure if im allowed to do this, bumps.

numbat
29th July 2009, 11:52
Try:


table->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);

junxuan
29th July 2009, 13:43
Thanks for the help but it doesnt seem to be working. :(

edit: it seems that it isnt the QTableView that is not expanding, rather it is the model that it is displaying that doesnt expand.

ChrisW67
30th July 2009, 08:17
You don't need line 23 in your original post.

Maybe:
table->horizontalHeader()->setStretchLastSection(true);
OR
table->horizontalHeader()->setResizeMode(0, QHeaderView::Stretch); are more to your liking?