class BarDelegate : public QAbstractItemDelegate{public:BarDelegate( QObject *parent = 0 );void paint( QPainter *painter,const QStyleOptionViewItem &option,const QModelIndex &index ) const;QSize sizeHint( const QStyleOptionViewItem &option,const QModelIndex &index ) const;};
QSize BarDelegate::sizeHint( const QStyleOptionViewItem &option,const QModelIndex &index ) const{return QSize( 45, 15 );}
void BarDelegate::paint( QPainter *painter,const QStyleOptionViewItem &option, const QModelIndex &index ) const{if( option.state & QStyle::State_Selected )painter->fillRect( option.rect, option.palette.highlight() );int value = index.model()->data( index, Qt::DisplayRole ).toInt();double factor = (double)value/100.0;painter->save();if( factor > 1 ){painter->setBrush( Qt::red );factor = 1;}elsepainter->setBrush( QColor( 0, (int)(factor*255), 255-(int)(factor*255) ) );painter->setPen( Qt::black );painter->drawRect( option.rect.x()+2, option.rect.y()+2,(int)(factor*(option.rect.width()-5)), option.rect.height()-5 );painter->restore();}
QTableView table;QStandardItemModel model( 10, 2 );for( int r=0; r<10; ++r ){QStandardItem *item = new QStandardItem( QString("Row %1").arg(r+1) );item->setEditable( false );model.setItem( r, 0, item );model.setItem( r, 1, new QStandardItem( QString::number((r*30)%100 )) );}table.setModel( &model );BarDelegate delegate;table.setItemDelegateForColumn( 1, &delegate );
void PatchItemDelegate::paint(QPainter *p, const QStyleOptionViewItem & o, const QModelIndex & i) const { const_cast<PatchItemDelegate*>(this)->m_Operation = i.data(OperationRole).toInt(); QItemDelegate::paint(p, o, i);}void PatchItemDelegate::drawDecoration(QPainter *p, const QStyleOptionViewItem & o, const QRect & r, const QPixmap & px) const { QItemDelegate::drawDecoration(p,o,r,px); if (m_Operation == None) return; int x = r.topLeft().x(); int y = r.topLeft().y() + r.height()/3; p->drawPixmap(x,y, QPixmap(m_IconFiles[m_Operation]));}