Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
373 views
in Technique[技术] by (71.8m points)

python - Changing the color of a QProgressbar()

I was wondering whether it's possible to change the color of a PyQt Progressbar?

I have the following code:

from PyQt4 import QtGui, QtCore
Pbar1 = QtGui.QProgressBar()
Pbar1.setParent(Frame1)
Pbar1.setGeometry(0, 0, 306, 30)
Pbar1.setValue(Frame1Value)
if Pbar1.value == 100
......Pbar1.setColor(Red)

Frame1Value is dependable on some early calculations, and to be assumed never calculates to exactly the same value.

I would like the progressbar to turn 'red' when the value is 100 (which the value is set limited at since a progressbar won't show values above 100%), so giving me a better visual image of the fact that the value is 'out of constraint'.

I am aware that .setColor isn't a known command for a Progressbar, but it's just to show my idea.

Does anyone know how to do this, or if it is even possible??

Thx in advance!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can sublass QProgressBar and use some style sheet see Customizing Qt Widgets Using Style Sheets and Customizing QProgressBar:

from PyQt4 import QtGui, QtCore

DEFAULT_STYLE = """
QProgressBar{
    border: 2px solid grey;
    border-radius: 5px;
    text-align: center
}

QProgressBar::chunk {
    background-color: lightblue;
    width: 10px;
    margin: 1px;
}
"""

COMPLETED_STYLE = """
QProgressBar{
    border: 2px solid grey;
    border-radius: 5px;
    text-align: center
}

QProgressBar::chunk {
    background-color: red;
    width: 10px;
    margin: 1px;
}
"""

class MyProgressBar(QtGui.QProgressBar):
    def __init__(self, parent = None):
        QtGui.QProgressBar.__init__(self, parent)
        self.setStyleSheet(DEFAULT_STYLE)

    def setValue(self, value):
        QtGui.QProgressBar.setValue(self, value)

        if value == self.maximum():
            self.setStyleSheet(COMPLETED_STYLE)

unfinished completed

Another solution would be to reassign a palette to the QProgressBar which will allow you to have a "style aware" component:

class MyProgressBar(QtGui.QProgressBar):
    def setValue(self, value):
        QtGui.QProgressBar.setValue(self, value)
        if value == self.maximum():
            palette = QtGui.QPalette(self.palette())
            palette.setColor(QtGui.QPalette.Highlight, 
                             QtGui.QColor(QtCore.Qt.red))
            self.setPalette(palette)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...