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:
MainWindow
::MainWindow(QWidget *parent
) : ui(new Ui::MainWindow)
{
ui->setupUi(this);
for(int i = 0; i < 10; i++){
item->setEditable(false);
model->setItem(i,0,item);
}
ui->tableView->setModel(model);
BarDelegate dg;
ui->tableView->setItemDelegateForColumn(1,&dg);
}
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
QStandardItemModel *model = new QStandardItemModel(10,2);
for(int i = 0; i < 10; i++){
QStandardItem *item = new QStandardItem(QString("Row: %1").arg(i));
item->setEditable(false);
model->setItem(i,0,item);
model->setItem(i,1,new QStandardItem(QString::number((i*30)%100)));
}
ui->tableView->setModel(model);
BarDelegate dg;
ui->tableView->setItemDelegateForColumn(1,&dg);
}
To copy to clipboard, switch view to plain text mode
But I get such error:
Capture.jpg
Here is BarDelegate declaration and definition:
{
public:
};
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;
};
To copy to clipboard, switch view to plain text mode
#include "bardelegate.h"
BarDelegate
::BarDelegate(QObject *parent
){
}
{
}
{
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;
}
else
painter
->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();
}
#include "bardelegate.h"
BarDelegate::BarDelegate(QObject *parent)
{
}
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;
}
else
painter->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();
}
To copy to clipboard, switch view to plain text mode
Bookmarks