David Doria
David Doria

Reputation: 10273

Using QStandardItemModel like QStringListModel

I am trying to use QStandardItemModel to do the same thing as QStringListModel (just for practice):

http://programmingexamples.net/wiki/Qt/ModelView/StandardItemModel

However, one cell shows up, but it is empty, as opposed to containing "text" as I would expect. Can anyone explain this? Is this the right way to go about using the QStandardItemModel (i.e. constructing QStandardItems and feeding them to the model?)

Upvotes: 0

Views: 1015

Answers (1)

Dave Mateer
Dave Mateer

Reputation: 17946

Actually, I'm surprised you aren't getting a crash. You are creating item0 on the stack, then passing a pointer to it to the QList. When that method leaves scope, item0 is deleted, and your list contains a pointer to the rotting area of memory that used to hold a QStandardItem.

{
  QStandardItem item0("test");
  QList<QStandardItem*> items;
  items.insert(0, &item0);  // Doesn't transfer ownership
  model->appendRow (items);
}  // Out of scope! Oh no!

Typically you would just create the new item, then add it using something like QStandardItemModel::setItem, like this:

QStandardItem *item0 = new QStandardItem("test");
model->setItem(0, 0, item);  // transfers ownership of item0 to the model

Upvotes: 3

Related Questions