Search code examples
qtqlistviewmodel-view

How to use Qt's Model-View programming


I'm trying to display some cards into a QListView but I'm really having trouble understanding how to use Qt's model/view pattern, and I can't find any simple examples.

Basically, I have two classes:

  • Card - my "model" which contains the name of the card, id, etc.

  • CardWidget - can load and render a Card object (display the card name and other info)

So how can I use Card and CardWidget to display a list of cards into a ListView? Do I need to change something to my classes, or should QListView be able to display them directly?

If someone could show me the basic steps or point me in the right direction that would be perfect.


Solution

  • See the documentation of QAbstractItemDelegate, which has an example of rendering items in a QTableView.

    Its not obvious what you are trying to do here - in a list view, you can render a view of an item which is not the same as having a widget in every cell. An item delegate can provide a widget as an editor and also how to render a cell's contents.

    If you actually want fixed widgets in the view, you could use QListView::openPersistentEditor on all the cells you want a fixed widget for. The item delegate should outline how to create an editor for the cell in question.