R4chi7
R4chi7

Reputation: 863

How to fill a rounded rectangle with different color segments by area in Qt?

I am new to Qt and I tried looking for examples online and the documentations but couldn't find something. I want something like this:

enter image description here

I tried it using a QLinearGradient but it isn't quite what I want. I want solid colors. Here's what I've tried:

void drawBackground ( QPainter * painter, const QStyleOptionViewItem & option, const QModelIndex & index ) const {
    QLinearGradient linearGrad(QPointF(option.rect.x(), 0), QPointF(option.rect.x() + option.rect.width(), 0));

    int total = index.data(StatisticsModel::TotalCount).toInt();
    linearGrad.setColorAt(0.0, QColor(255, 255, 255, 0));

    int sum = 0;
    for (int i = 7; i >= 1; i--) {
        int count = index.data(StatisticsModel::Grade0 + i).toInt();

        if (count) {
            sum += count;
            linearGrad.setColorAt(1.0-((double)(total-sum))/total, Prefs::gradeColor(i));

        }
    }


    QRect rect(option.rect);
    rect.adjust(1, 1, -1, -1);

    QPainterPath path;
    path.addRoundedRect( rect, 2.0, 2.0 );
    painter->setBrush(QBrush(linearGrad));
    painter->drawPath(path);
}

Any help would be appreciated.

Upvotes: 1

Views: 1999

Answers (1)

Predelnik
Predelnik

Reputation: 5246

Well the best way to color rounded rectangle like this I guess would be to create QPainterPath for it then construct normal rectangles which should be of specified color intersect them with initial rounded rectangle QPainterPath using function QPainterPath::intersected and draw them, selecting corresponding solid color brush and using function drawPath

Upvotes: 3

Related Questions