Filling a cell background in tableview based on percentage

  • Hi,
    I am a beginner to QT. My intention is to fill the BackGround of a cell in TableView partially.
    For Example : I want only 50% of the cell to be coloured or 25% .It depends on some parameters like students score in his subject.

    Thanks in advance.

  • Moderators

    @Abhi_oct30 It you are talking about QTableView then you can use QStyledItemDelegate to do custom painting or at the best you can also use a progressbar with fixed value.
    Here's an example using QAbstractItemDelegate

  • hi, intention is partially completed.But the problem is progress bar is and the value are displayed side by side.I want the progress bar to be as the background for the value.0_1484231294431_upload-ad9092a7-4b20-4e0e-9f5e-f371754ace91

  • @Abhi_oct30
    I find that set progress bar's alignment to center may be what you want

  • #include <QStyledItemDelegate>
    #include <QPainter>
    #include <QApplication>
    class BarDelegate : public QStyledItemDelegate
        BarDelegate(QObject* parent = Q_NULLPTR)
        void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const Q_DECL_OVERRIDE
            QStyleOptionViewItem opt = option;
            initStyleOption(&opt, index);
            // here decide how much of the background you want filled, from 0 to 1
            // as an example here I use whatever is in Qt::UserRole as the percentage
            const double fillPercent =;
            painter->drawRect(QRect(opt.rect.topLeft(), QSize(static_cast<double>(opt.rect.width())*fillPercent, opt.rect.height())));
            opt.backgroundBrush = QBrush();
            const QWidget *widget = option.widget;
            QStyle *style = widget ? widget->style() : QApplication::style();
            style->drawControl(QStyle::CE_ItemViewItem, &opt, painter, widget);

    Now you can set the background either by stylesheet or by defining the Qt::BackgroundRole data

Log in to reply

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.