开发者

How do I detect row selections in QListView <- > QAbstractListModel with Item Delegate?

It seems there is zero built-in selection support with my choice of QListView -> QAbstractListModel. Do I have to write everything from scratch? the catching of a selection event in the UI, the marking of the model item as selected, etc? It seems there is no out-of-the-box support for this.

the weird thing is that there is a QItemSelectionModel that does support this, 开发者_StackOverflow中文版but you cannot use it with QListView as it’s not derived from QAbstract….

Should my model class use multiple inheritance to inherit both from QItemSelectionModel and QAbstractListModel? Otherwise I don’t see how I can avoid having to re-writing this functionality myself.

My final goal is for the delegate that draws my items to know if the item is selected, both in the paint and the sizeHint function.


QListView is derived from QAbstractItemView, which has a method to get the selection model:

QItemSelectionModel *selectionModel = myView->selectionModel();

This method returns a pointer to the selection model, which is long-lived, i.e., you can save the pointer, connect to its signals, etc.


The answer given by Daniel is correct, but it is better to show it with an example suitable for beginners:

class MyCustomModel : public QAbstractListModel
{
    Q_OBJECT
public:
    ImageCollectionModel(QObject *parent, MyCustomCollection *data);
        : QObject(parent)
        , m_myData(data)
    {
    }

public slots:
    void onSelectedItemsChanged(QItemSelection selected, QItemSelection deselected)
    {
        // Here is where your model receives the notification on what items are currently
        // selected and deselected
        if (!selected.empty())
        {
            int index = selected.first().indexes().first().row();
            emit mySelectedItemChanged(m_myData->at(index));
        }
    }

signals:
    void mySelectedItemChanged(MyCustomItem item);

private:
    MyCustomCollection *m_myData;

    // QAbstractItemModel interface
public:
    int rowCount(const QModelIndex &) const override;
    QVariant data(const QModelIndex &index, int role) const override;
};

When you pass your custom model to the QListView, that's a great opportunity to connect it:

ui->myListView->setModel(m_myModel);
connect(ui->myListView->selectionModel(), SIGNAL(selectionChanged(QItemSelection, QItemSelection)),
        m_myModel, SLOT(onSelectedItemsChanged(QItemSelection, QItemSelection)));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜