Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the color of the text of a QProgressBar with its value?

I don't know how to change the color of the text partially in the progress bar when its value becomes nearly 50%. This effect comes automatically in the fusion style progress bar (picture below). Does anyone know how this is done ?

Fusion style progress bar

like image 655
Shiva Avatar asked Aug 01 '13 07:08

Shiva


3 Answers

Too lazy to write working example code, much less making a screenshot. Not even for 50 reps. :-)

However, the question was somewhat interesting. I had no idea how such a two colored text could be done. So I checked: http://qt.gitorious.org/qt/qtbase/blobs/stable/src/widgets/styles/qfusionstyle.cpp Line 1450ff (http://qt.gitorious.org/qt/qtbase/blobs/stable/src/widgets/styles/qfusionstyle.cpp#line1450).

    QRegion rightRect = rect;
    rightRect = rightRect.subtracted(leftRect);
    painter->setClipRegion(rightRect);
    painter->setPen(flip ? alternateTextColor : textColor);
    painter->drawText(rect,
                      bar->text,
                      QTextOption(Qt::AlignAbsolute|
                                   Qt::AlignHCenter|
                                   Qt::AlignVCenter));
    if (!leftRect.isNull()) 
    {
        painter->setPen(flip ? textColor : alternateTextColor);
        painter->setClipRect(leftRect);
        painter->drawText(rect,
                 bar->text,
                 QTextOption(Qt::AlignAbsolute|
                              Qt::AlignHCenter|
                              Qt::AlignVCenter));
    }

Basically the text is drawn two times into the same rectangle. Each time with an appropriate clipping. Easy if you know how. :-)

like image 183
Greenflow Avatar answered Nov 15 '22 13:11

Greenflow


From my point of view the best, and probably the easiest, way to do this is to change the pallet for the QProgressBar widget:

    QPalette palette = progressBar->palette()
    palette.setColor(QPalette::Text, textColor)
    palette.setColor(QPalette::HighlightedText, textColor)
    progressBar->setPalette(palette)
like image 39
Alex Avatar answered Nov 15 '22 12:11

Alex


"The setBackgroundRole method let you use a color role for the background, which means one of the predefined color of the style applied to the widget. So your are basically limited to the style and its colors."

enter image description here

Background solution:

    value = 65
    self.progressBar.setProperty("value", value)

    if value < 50:
        self.progressBar.setStyleSheet("QProgressBar::chunk { background-color: black; }")
    else:
        self.progressBar.setStyleSheet("QProgressBar::chunk { background-color: black; } QProgressBar { color: white; }")
like image 32
Fahri Güreşçi Avatar answered Nov 15 '22 13:11

Fahri Güreşçi