Quick question
Is there an easy/quick way to map a QListWidget
or QStandardItemModel
(for QListView
) item to my application logic?
Complete Question
Note: I will use undistinctly both
QListWidget
or QListView and itsQStandardItemModel. From my current point of view for this question, switching from one to another is trivial.
I face usually the need to have a QListView
or equivalent in an HMI, which shows some text value and need to react on selection/click.
In the SLOT
, in order to perform the required action, the row need to be identified. Qt::DisplayRole
is NOT appropriate because some texts could be duplicated and QStrings are not the best way to identify data in Computer Science.
// Click on a row
connect( &myView, &QListView::clicked,
[&myView, this]( const QModelIndex &idx)
{
// E.G. need to update the database for this row. Which row?
});
Possible solutions:
- Maintain a
map
to retrieve the ID from theQModelIndex
row. - Save in the model row any ID, making easy to apply any operation.
First option is tedious: it requires to connect the model for keeping the map and the model synchronized.. Same logic again and again.
Second option seem by far the best: I save the (e.g. database id) and use it afterward; But, QListView
model (up to what I know) does NOT include this very friendly and useful ID. So until now I had extended again and again the models for QListView
.
How to map the QModelIndex back to my application logic? Do I really have to extend the model for that simple operation?
RELATED QUESTION: QTreeView: maintaining mapping between QModelIndex and underlying data