Hello all.
I'm reading Johan Thelin's "Foundation of Qt Development" And I'm at Costum View. It is little bit difficult and i write code such as in the book.
I Dropped TableView on a form and then:
MainWindow Constructor:
Qt Code:
  1. MainWindow::MainWindow(QWidget *parent) :
  2. QMainWindow(parent),
  3. ui(new Ui::MainWindow)
  4. {
  5. ui->setupUi(this);
  6.  
  7.  
  8. for(int i = 0; i < 10; i++){
  9. QStandardItem *item = new QStandardItem(QString("Row: %1").arg(i));
  10. item->setEditable(false);
  11. model->setItem(i,0,item);
  12.  
  13. model->setItem(i,1,new QStandardItem(QString::number((i*30)%100)));
  14. }
  15.  
  16. ui->tableView->setModel(model);
  17.  
  18. BarDelegate dg;
  19. ui->tableView->setItemDelegateForColumn(1,&dg);
  20. }
To copy to clipboard, switch view to plain text mode 

But I get such error:
Capture.jpg

Here is BarDelegate declaration and definition:
Qt Code:
  1. class BarDelegate : public QAbstractItemDelegate
  2. {
  3. public:
  4. BarDelegate(QObject *parent = 0);
  5.  
  6. void paint(QPainter *painter,const QStyleOptionViewItem &option,const QModelIndex *index) const;
  7.  
  8. QSize sizeHint(const QStyleOptionViewItem *option,const QModelIndex &index) const;
  9. };
To copy to clipboard, switch view to plain text mode 

Qt Code:
  1. #include "bardelegate.h"
  2.  
  3. BarDelegate::BarDelegate(QObject *parent)
  4. {
  5.  
  6. }
  7. QSize BarDelegate::sizeHint(const QStyleOptionViewItem *option, const QModelIndex &index) const
  8. {
  9. return QSize(45,15);
  10. }
  11.  
  12. void BarDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex *index) const
  13. {
  14. if(option.state & QStyle::State_Selected)
  15. painter->fillRect(option.rect,option.palette.highlight() );
  16.  
  17. int value = index->model()->data(index,Qt::DisplayRole).toInt();
  18. double factor = (double)value/100.0;
  19.  
  20. painter->save();
  21.  
  22. if(factor > 1)
  23. {
  24. painter->setBrush(Qt::red);
  25. factor = 1;
  26. }
  27. else
  28. painter->setBrush(QColor(0,(int)(factor*255),255-(int)(factor*255)));
  29.  
  30. painter->setPen(Qt::black);
  31. painter->drawRect(option.rect.x()+2,option.rect.y()+2,(int)(factor*(option.rect.width()-5)),option.rect.height()-5);
  32.  
  33. painter->restore();
  34. }
To copy to clipboard, switch view to plain text mode