PDA

View Full Version : An example 'Spin Box Delegate' code does not work using a tableView



tonnot
21st September 2010, 19:27
This is the original code :


int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QStandardItemModel model(4, 2);
QTableView tableView;
tableView.setModel(&model);
tableView.horizontalHeader()->setStretchLastSection(true);
for (int row = 0; row < 4; ++row) {
for (int column = 0; column < 2; ++column) {
QModelIndex index = model.index(row, column, QModelIndex());
model.setData(index, QVariant((row+1) * (column+1)));
}
}

tableView.setWindowTitle(QObject::tr("Spin Box Delegate"));
tableView.show();
return app.exec();
}

And this is my code (I use a TableView out on a window using Designer)


QStandardItemModel modelo(4, 2);
ui->tableView->setModel(&modelo);
ui->tableView->horizontalHeader()->setStretchLastSection(true);
for (int row = 0; row < 4; ++row) {
for (int column = 0; column < 2; ++column) {
QModelIndex index = modelo.index(row, column, QModelIndex());
modelo.setData(index, QVariant((row+1) * (column+1)));
}
}


(I only delete the 'delegate' code, in order to simply test how it works)
Ok, in my case I see the table but i dont see the cells neither its content.
What happens ?

tbscope
21st September 2010, 19:36
You defined your model on the stack and it gets deleted at the end of the function (which I guess is your constructor)

tonnot
22nd September 2010, 07:15
Thank you for your answer.
But... I dont understand your explanation...
The only difference between the original code and mine is that I use a tableView accesdesd 'via' the ui->.
And, how can I avoid the destruction ?
Thanks for your patience.

Lykurg
22nd September 2010, 07:23
The only difference between the original code and mine is that I use a tableView accesdesd 'via' the ui->.And that is exactly the difference why their code is working and yours not! And it is basic C++, so take any c++ book and read about dynamic and static allocation and how long objects lives.

ChrisW67
22nd September 2010, 22:34
Thank you for your answer.
But... I dont understand your explanation...
Items allocated on the stack, like modelo, only exist to the end of the enclosing block (usually a method/function). You need to look at the differences between where you have modelo declared and where the original example has its model. What is the lifetime of the two objects?