Home > OS >  QStyledItemDelegate / QAbstractItemDelegate for QListView
QStyledItemDelegate / QAbstractItemDelegate for QListView

Time:05-19

My aim is to create something like contact app, where I can list contacts and choose it to see information about person. I figure out that one of the possible solution is to use QListView QStyledItemDelegate / QAbstractItemDelegate. The information about it is very difficult so I don't understand it clearly;

(Contact should look something like https://www.sketchappsources.com/free-source/4395-ios-contacts-screen-app-sketch-freebie-resource.html)

So how should I use QAbstractItemDelegate ( I heard that I must reimplement paintEvent )?

CodePudding user response:

I suggest you to start with a data model.

  1. Use QStandardItemModel class for beginning and populate it with QStandardItem class instances. It would allow you to set icon, text, font, background, size and other properties for items. Refer to https://doc.qt.io/qt-5/qstandarditemmodel.html#details
  2. Set your model to QListView using setModel
  3. To handle items clicked connect to QListView's clicked signal.

To render items in more complex way you should

  1. Override QStyledItemDelegate class and it's paint and sizeHint methods. In the paint method you should implement rendering and your sizeHint method should return a valid size for items. Refer to https://doc.qt.io/qt-5/qabstractitemdelegate.html#details
  2. To get item data to render use data method of QModelIndex reference that is passed to paint method. Use different roles to get appropriate data. Refer to https://doc.qt.io/qt-5/qt.html#ItemDataRole-enum
  3. Use your delegate class by setting it to QListView by setItemDelegate.

Model should be set to QListView and item clicks are handled in same way.

  • Related