QTreeview does not update correctly when items are

2019-07-26 20:25发布

I've got a treeview, which should show the content of an own datacollection to achieve this, I've implemented a new model for the treeview. When I add an object to any parent Item everything works fine and the new Item is shown in the view, but when I try to add an item to the rootitem, this item does not show up until I add an Object to another parentitem or I reset the model.

My method to add rows to the model looks like this:

bool TreeModel::insertRows(int row, int count, const QModelIndex &parent, DataObject *object, QString name, QString path)
{
  if (!parent.isValid())
     return false;

  DataCollection* dataCollection = static_cast<DataCollection*>(parent.internalPointer());

  beginInsertRows(parent, dataCollection->Size(), dataCollection->Size());
  dataCollection->AddData(object, name.toStdString(), path.toStdString());
  endInsertRows();


  return true;
}

How can I achieve an update of the view when I am adding an item to the rootelement?

2条回答
趁早两清
2楼-- · 2019-07-26 20:38

You don't use beginInsertRows in a good way:

void QAbstractItemModel::beginInsertRows(const QModelIndex & parent, int first, int last)

But you are passing twice the size of items: that seems strange to me. Anyway, if your model is a subclass of QStandardItemModel (and not QAbstractItemModel), there's a very convenient method that you can use:

QStandardItem * QStandardItemModel::invisibleRootItem() const

From the documentation:

Returns the model's invisible root item. The invisible root item provides access to the model's top-level items through the QStandardItem API, making it possible to write functions that can treat top-level items and their children in a uniform way; for example, recursive functions involving a tree model.

Note: Calling index() on the QStandardItem object retrieved from this function is not valid.

查看更多
Summer. ? 凉城
3楼-- · 2019-07-26 20:43

I found a really easy way to solve this - all you have to do is add emit layoutChanged(); to your insertRows() function.

Initially I was emitting dataChanged() but apparently it only affects the data of the item, the branch-related data is not part of an item.

It's not as efficient as doing it properly with beginInsertRows() and endInsertRows() but if the amount of items you have is not massive this solution should be more than sufficient.

查看更多
登录 后发表回答