How to determine row selection in QListView & # 8596; QAbstractListModel with delegate elements?

There seems to be zero native select support with my choice of QListView -> QAbstractListModel. Do I need to write everything from scratch? capturing the selection event in the user interface, marking the selected model element, etc.? There seems to be no ready support for this.

It is strange that there is a QItemSelectionModel that supports this, but you cannot use it with a QListView, since it is not obtained from QAbstract ....

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

My ultimate goal is for the delegate to draw my objects to see if the item is selected in both the paint and the sizeHint function.

+4
source share
2 answers

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

QItemSelectionModel *selectionModel = myView->selectionModel(); 

This method returns a pointer to a selection model that is durable, i.e. you can save the pointer, connect to its signals, etc.

+6
source

Daniel's answer is correct, but it’s 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 QListView, this is 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
source

Source: https://habr.com/ru/post/1344665/


All Articles