class BackgroundDelegate : public QStyledItemDelegate {
public:
explicit BackgroundDelegate(QObject *parent = 0)
: QStyledItemDelegate(parent){}
void paint(QPainter *painter, const QStyleOptionViewItem &option,
const QModelIndex &index) const {
// Fill the background before calling the base class paint
// otherwise selected cells would have a white background
QVariant background = index.data(Qt::BackgroundRole);
if (background.canConvert<QBrush>())
painter->fillRect(option.rect, background.value<QBrush>());
// the comment below makes selection transparent
//QStyledItemDelegate::paint(painter, option, index);
// To draw a border on selected cells
if(option.state & QStyle::State_Selected) {
painter->save();
QPen pen(Qt::black, 2, Qt::SolidLine, Qt::SquareCap, Qt::MiterJoin);
int w = pen.width()/2;
painter->setPen(pen);
painter->drawRect(option.rect.adjusted(w,w,-w,-w));
painter->restore();
}
}
};
然後 table->setItemDelegateForColumn(2, new BackgroundDelegate(this));