c++ - QTreeView:如何中止选择更改

标签 c++ qt qtreeview

我的小部件中有一个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/

相关文章:

c++ - 在 amd64 架构上用 C++ 将图像缓冲区 blit 到另一个缓冲区的 xy 偏移的最快方法

c++ - 是否存在 self 分配有用的情况?

c# - 如何编写用于将 Qt 信号映射到 C# 事件的包装类(通过 C++/CLI)

Qt 信号槽交互。

resize - 如何调整 QTreeView 和 QStandardItemModel 中的行大小?

python - 具有多个 header 的 QStandardItemModel - 将 QTreeView header 与模型分离

c++ - 比较 Google Test 或 Google Mock 中的特征矩阵

c++ - 有人可以在谷歌驱动器中推荐一个用于编辑 C++ 文件的应用程序吗?

c++ - 信号与槽QT

c++ - 自动展开qtreeview中委托(delegate)的qcombobox