QTableView带可编辑进度条

main文件与上一个例子完全一致,也使用QStandardItemModel,关键是有这句:QStandardItem.setEditable(false); 

继承QAbstractItemDelegate后,覆盖4个函数(全部经过验证,都是自带后覆盖):

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;

QWidget *createEditor( QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index ) const;
void setEditorData( QWidget *editor, const QModelIndex &index ) const;
void setModelData( QWidget *editor, QAbstractItemModel *model, const QModelIndex &index ) const;
void updateEditorGeometry( QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index ) const;
};

进度条本身的代码不贴了,直接贴这四个函数:

QWidget *BarDelegate::createEditor( QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index ) const
{
  QSlider *slider = new QSlider( parent );
  
  slider->setAutoFillBackground( true );
  slider->setOrientation( Qt::Horizontal );
  slider->setRange( 0, 100 );
  slider->installEventFilter( const_cast<BarDelegate*>(this) );
  
  return slider;
}

void BarDelegate::updateEditorGeometry( QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index ) const
{
  editor->setGeometry( option.rect );
}

void BarDelegate::setEditorData( QWidget *editor, const QModelIndex &index ) const
{
  int value = index.model()->data( index, Qt::DisplayRole ).toInt();
  static_cast<QSlider*>( editor )->setValue( value );
}

void BarDelegate::setModelData( QWidget *editor, QAbstractItemModel *model, const QModelIndex &index ) const
{
  model->setData( index, static_cast<QSlider*>( editor )->value() ); // 这句很关键,把model的数据也修改了
}

 

你可能感兴趣的:(QTableView)