如何在Qt中刷新TreeModel?
我有一个如何在Qt中刷新TreeModel?,qt,qtreeview,qabstractitemmodel,Qt,Qtreeview,Qabstractitemmodel,我有一个TreeModel,其中加载了一些数据。我的应用程序中有一个单选按钮,单击该按钮时应使用新数据更新TreeModel 我在切换单选按钮时尝试了以下方法,但均无效: 发射layoutChanged emit layoutChanged(); emit dataChanged(QModelIndex(), QModelIndex()); 发出dataChanged emit layoutChanged(); emit dataChanged(QModelIndex(), QMod
TreeModel
,其中加载了一些数据。我的应用程序中有一个单选按钮,单击该按钮时应使用新数据更新TreeModel
我在切换单选按钮时尝试了以下方法,但均无效:
- 发射
layoutChanged
emit layoutChanged();
emit dataChanged(QModelIndex(), QModelIndex());
- 发出
dataChanged
emit layoutChanged();
emit dataChanged(QModelIndex(), QModelIndex());
- 递归访问树中的每个节点并发送数据
void TreeView::getLastExpandedState(const QModelIndex& parent) { bool isExpand = isExpanded(parent); if (!isExpand) { return; } int rows = model()->rowCount(parent); for (int rowNum = 0; rowNum < rows ; ++rowNum) { QModelIndex childIndex = model()->index(rowNum, 0, parent); model->emitChange(parent,childIndex); getLastExpandedState(childIndex); } } void TreeModel::emitChange(const QModelIndex& parent,const QModelIndex& childIndex) { emit dataChanged(parent,childIndex); }
void TreeView::getLastExpandedState(常量QModelIndex&parent) { bool isExpand=isExpanded(父级); 如果(!isExpand){ 返回; } int rows=model()->rowCount(父级); 对于(int-rowNum=0;rowNum
index(rowNum,0,父级); 模型->更改(父项、子项索引); getLastExpandedState(childIndex); } } void TreeModel::emitChange(常量QModelIndex&parent,常量QModelIndex&childIndex){ 发出数据更改(父、子索引); }
如何解决这个问题?你提到的答案充其量是令人困惑的,可能是错误的 模型代码需要为模型
data
方法返回的数据已更改的任何矩形单元格发出dataChanged
信号。例如,请参见问答,其中涉及一些细节
请注意,dataChanged
信号中的参数不应该是父参数和子参数-它们应该是“左上”和“右下”。他们需要有相同的父母,也需要不同。因此,您不需要迭代行并为每行发出信号。您可以为所有已更改的行发送组合信号
但您确实需要为每个父级(数据已更改的位置)发送一个信号,向该父级的左上单元格和右下单元格发送信号。因此,您可能会在(0,0,parent)
处为左上角单元格创建索引,在(rows,cols,parent)
处为右下角单元格创建另一个索引,然后为这对索引发送信号