我的小部件中有一个QTreeView
。当在 View 中选择一个项目时,我有
在详细信息窗口中更新一系列信息小部件的信号处理程序
关于所选项目。然后,用户可以编辑项目详细信息并提交
更改回模型。
更改此选择后,如果详细信息 View 中的数据已被编辑
发生这种情况时,我会在替换数据之前向用户显示一个确认对话框
当选择一个新的项目。如果用户取消,我要设置选择
树回到以前的样子。
我的插槽已连接,如下所示:
auto selection_model = treeview->selectionModel();
connect(
selection_model, &QItemSelectionModel::currentChanged,
this, &Editor::on_tree_selection_changed
)
在我的广告位中,代码的结构如下:
void on_tree_selection_changed(QModelIndex const& index, QModelIndex const& previous)
{
if(not confirm_editor_discard())
{
// user does not want to override current edits
log.trace("cancel item selection change");
using SF = QItemSelectionModel::SelectionFlags;
auto sm = treeview->selectionModel();
sm->setCurrentIndex(previous, SF::SelectCurrent | SF::Rows);
}
else
{
// user wants to discard, so update the details view.
log.trace("discard pending edits");
set_details_from_model(index);
}
}
但是,当前索引设置回前一个似乎没有
影响TreeView;它仍将新选择的项目显示为选中状态,并且
由于详细信息中显示的项目是
而不是在树中显示的那个。
预期的行为是重新选择以前选择的项目,好像没有
完全进行了新选择。
最佳答案
显然,在调用QTreeView
插槽时,currentChanged
会忽略来自选择模型的任何更新。
这里的解决方案是将广告位称为QueuedConnection
,因此connect
行将如下所示:
connect(
selection_model, &QItemSelectionModel::currentChanged,
this, &Editor::on_tree_selection_changed,
Qt::QueuedConnection // <-- connection must be queued.
)
这将确保选择模型的选择更改不会直接在广告位调用中发生。
关于c++ - QTreeView:如何中止选择更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50218443/