是否有办法获得QAbstractItemView
中当前可见项目的列表?并且,如果可能的话,接收关于此列表更改的任何通知。
乌利希期刊指南:我问的是非平面结构的QAbstractItemView
或QTreeView
,而不是QTableView
。
Upd2:我实现树形视图模型与复选框。我想要下一个行为(相同的检查/取消检查):
- 如果一个复选框被选中,那么所有子框必须被选中
- 如果所有子复选框都被选中,那么父复选框也应该被选中。parent的parent也是一样,等等…
检查状态由外部数据源监视/修改,因此我需要一种机制来更新所有更改的子/父节点。dataChanged
信号对我来说是不够的,因为要建立一个所有更改的QModelIndex
列表进行更新是非常广泛的。这是完全没有必要的,因为所有的新数据都将从QAbstractItemModel::data
中取出。
我发现下一个肮脏的hack来更新所有的项目:emit dataChanged( QModelIndex(), QModelIndex() );
,但它是无文档的无效索引。
所以,我需要一种方法来强制所有可见的项目重新绘制他们的内容与新的数据。
您可以通过调用
来获取左上方和右下方的单元格:tableview->indexAt(tableview->rect().topLeft())
tableview->indexAt(tableview->rect().bottomRight())
要获得更改通知,重新实现qabstractscrollarea
的虚函数scrollContentsBy
在滚动视图端口时调用该函数。调用QTableView::scrollContentsBy然后做任何你需要的
对于QTreeView
,可以像这样遍历可见项列表:
QTreeView& tv (yourTreeView);
// Get model index for first visible item
QModelIndex modelIndex = tv.indexAt(tv.rect().topLeft());
while (modelIndex.isValid())
{
// do something with the item indexed by modelIndex
...
// This navigates to the next visible item
modelIndex = tv.indexBelow(modelIndex);
}
方法1
i, j = table.indexAt(table.rect().topLeft()).row(), table.indexAt(table.rect().bottomLeft()).row() - 1
方法2
i, j = table.rowAt(0), table.rowAt(table.height()) - 1
我认为不需要可见项列表。在正确的模型实现的情况下,所有项目都自动更新。实施的难点——强迫孩子和家长更新。我写了下面的代码:
bool TreeModel::setData( const QModelIndex &index, const QVariant &value, int role )
case Qt::CheckStateRole:
{
TreeItemList updateRangeList; // Filled with items, in which all childred must be updated
TreeItemList updateSingleList; // Filled with items, which must be updated
item->setCheckState( value.toBool(), updateRangeList, updateSingleList ); // All magic there
foreach ( TreeAbstractItem *i, updateRangeList )
{
const int nRows = i->rowCount();
QModelIndex topLeft = indexForItem( i->m_childs[0] );
QModelIndex bottomRight = indexForItem( i->m_childs[nRows - 1] );
emit dataChanged( topLeft, bottomRight );
}
foreach ( TreeAbstractItem *i, updateSingleList )
{
QModelIndex updateIndex = indexForItem( i );
emit dataChanged( updateIndex, updateIndex );
}
}
我总是更新整个QAbstractTableModel:
emit dataChanged(index(0, 0), index(rowCount(), columnCount()-1)); // update whole view