ui->tableView->setItemDelegate(new ProgressBarDelegate());
ui->tableView->setItemDelegate(new ProgressBarDelegate());
To copy to clipboard, switch view to plain text mode
ProgressBarDelegate is a class derived from QStyledItemDelegate and here's the paint method:
{
if (!index.isValid())
return;
int col = index.column();
if (col == 5)
{
int progress = index.data().toInt();
progressBarOption.
rect = QRect(option.
rect.
x(), option.
rect.
y() + 5 , option.
rect.
width(), option.
rect.
height() / 1.5);
if (progress == 100)
{
QApplication::style()->drawItemText
(painter, option.
rect, Qt
::AlignCenter|Qt
::AlignVCenter, option.
palette,
true,
QString::number(progress
) + "%");
}
else
{
progressBarOption.minimum = 0;
progressBarOption.maximum = 100;
progressBarOption.progress = progress;
progressBarOption.
text = QString::number(progress
) + "%";
progressBarOption.textVisible = true;
progressBarOption.textAlignment = Qt::AlignCenter|Qt::AlignVCenter;
}
}
else
{
QStyledItemDelegate::paint(painter, option, index);
}
return;
}
void ProgressBarDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
if (!index.isValid())
return;
int col = index.column();
if (col == 5)
{
int progress = index.data().toInt();
QStyleOptionProgressBar progressBarOption;
progressBarOption.rect = QRect(option.rect.x(), option.rect.y() + 5 , option.rect.width(), option.rect.height() / 1.5);
if (progress == 100)
{
QApplication::style()->drawItemText(painter, option.rect, Qt::AlignCenter|Qt::AlignVCenter, option.palette, true, QString::number(progress) + "%");
}
else
{
progressBarOption.minimum = 0;
progressBarOption.maximum = 100;
progressBarOption.progress = progress;
progressBarOption.text = QString::number(progress) + "%";
progressBarOption.textVisible = true;
progressBarOption.textAlignment = Qt::AlignCenter|Qt::AlignVCenter;
QApplication::style()->drawControl(QStyle::CE_ProgressBar, &progressBarOption, painter);
}
}
else
{
QStyledItemDelegate::paint(painter, option, index);
}
return;
}
To copy to clipboard, switch view to plain text mode
So you'll see that the delegate is set at the view level and then in the paint method, I only override how the progress bar I want in column 5 is drawn and I call the base class paint method for all other columns.
Bookmarks