QTreeview does not update correctly when items are added to the root

帅比萌擦擦* 提交于 2019-12-24 11:28:47

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/23364207/qtreeview-does-not-update-correctly-when-items-are-added-to-the-root

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!