1

我有一棵树,其父节点为 A 、 B 、 C 。每个节点都有子节点。我想只允许一个父节点下的子节点进行多项选择。任何指针,我如何使用 QTreeview 做到这一点?

A-> D,E,F   
B-> G, H, I   
C-> J, K, L

因此,应允许 D、E、F 或 G、H、I 多选,而不是 D、G、H 等。

谢谢

4

1 回答 1

2

这是一种效果很好的方法。为您的视图分配模型后,连接到 selectionModel 的 changed 参数。

connect(treeView->selectionModel(), SIGNAL(selectionChanged(QItemSelection, QItemSelection)), SLOT(processSelection(QItemSelection, QItemSelection)));

然后编写一个函数,每次更改时都会更改选择,以符合您的要求。

void MyClass::processSelection(const QItemSelection& selected, const QItemSelection& deselected)
{
    if (selected.empty())
        return;

    QItemSelectionModel* selectionModel = treeView->selectionModel();

    QItemSelection selection = selectionModel->selection();
    const QModelIndex parent = treeView->currentIndex().parent();

    QItemSelection invalid;

    Q_FOREACH(QModelIndex index, selection.indexes())
    {
        if (index.parent() == parent)
            continue;

        invalid.select(index, index);
    }

    selectionModel->select(invalid, QItemSelectionModel::Deselect);
}

我注意到在大树的大面积上拖动范围时出现了一些非常小的减速,但除此之外它似乎运行良好。

于 2015-05-01T11:01:34.853 回答