[Interest] Sharing QItemSelectionModel with multiple views/proxy models

Jeremy Katz jeremy.k.list at gmail.com
Sat Sep 26 07:55:25 CEST 2020


On 24/Sep/20 13:12, Murphy, Sean wrote:
> What's the best way to share selections between views when you're
> dealing with different levels of models and proxy models between the
> separate views?
> 
> I've got the following setup: -  myData: a data only class that holds
> the underlying values to be displayed - dataModel: a model that
> operates directly on myData - proxyModel:  a proxy model that
> dataModel as source model - view1: a QTableView that uses dataModel
> for its model - view2: another QTableView that uses proxyModel for
> its model
> 
> I'm trying to get selections on one view to be replicated to the
> other[...]> So how do I connect things up so that selections on view1 are
> propagate through the proxy model, and then the respective indices
> are selected in view2, and vice versa?

Use QAbstractProxyModel::mapToSource() and mapFromSource(), or
mapSelectionToSource() and mapSelectionFromSource().

Eg:
QObject::connect(
    sourceSelectionModel,
    &QItemSelectionModel::selectionChanged,
    proxySelectionModel,
    [&](const QItemSelection &set) {
        QItemSelection newSet = proxyModel->mapSelectionFromSource(set);
        proxySelectionModel->select(newSet,
            QItemSelectionModel::ClearAndSelect);
    });

Repeat for each of the signals for QItemSelectionModel changes that
should be mirrored, for each selection model. You can save some overhead
by tracking which view originated the change, but QItemSelectionModel
will detect empty change sets.


More information about the Interest mailing list