Qt: click buttons for each row drawn with QAbstractItemDelegate

I would like to draw "clickable" icons (or buttons) in each row of a QListView. I use my own custom QAbstractItemDelegate class for drawing. These buttons can change with the user status of the row (I have access to the basic data structure during drawing).

What is the best way to approach this?

+7
source share
1 answer

DISCLAIMER: This may not be the best way, but here is the way that you have full control. We found it necessary to do this with the help of drawing flags.

You can inherit from QStyledItemDelegate (or QAbstractItemDelegate may work .. didn't try) and override the paint and editorEvent . You use QStyle::drawControl() (after setting the appropriate style options) to draw the control in paint , and then manually check for the mouse in editorEvent and do something with it. If memory serves me correctly, this code was pretty much inspired (cough, copied, cough, cough) by looking at the Qt source code for QStyledItemDelegate .

 void CheckBoxDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { bool checked = index.model()->data(index, Qt::DisplayRole).toBool(); if (option.state & QStyle::State_Selected) { painter->setPen(QPen(Qt::NoPen)); if (option.state & QStyle::State_Active) { painter->setBrush(QBrush(QPalette().highlight())); } else { painter->setBrush(QBrush(QPalette().color(QPalette::Inactive, QPalette::Highlight))); } painter->drawRect(option.rect); } QStyleOptionButton check_box_style_option; check_box_style_option.state |= QStyle::State_Enabled; if (checked) { check_box_style_option.state |= QStyle::State_On; } else { check_box_style_option.state |= QStyle::State_Off; } check_box_style_option.rect = CheckBoxRect(option); QApplication::style()->drawControl(QStyle::CE_CheckBox, &check_box_style_option, painter); } bool CheckBoxDelegate::editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index) { if ((event->type() == QEvent::MouseButtonRelease) || (event->type() == QEvent::MouseButtonDblClick)) { QMouseEvent *mouse_event = static_cast<QMouseEvent*>(event); if (mouse_event->button() != Qt::LeftButton || !CheckBoxRect(option).contains(mouse_event->pos())) { return true; } if (event->type() == QEvent::MouseButtonDblClick) { return true; } } else if (event->type() == QEvent::KeyPress) { if (static_cast<QKeyEvent*>(event)->key() != Qt::Key_Space && static_cast<QKeyEvent*>(event)->key() != Qt::Key_Select) { return false; } } else { return false; } bool checked = model->data(index, Qt::DisplayRole).toBool(); return model->setData(index, !checked, Qt::EditRole); } 
+6
source

All Articles