I'm wondering if there is a way to customize a color of the progress bar (QtGui.QProgressBar). Let's say we would want to make it green when bar reaches 100%.
Here is a working example:
import sys, time
from PyQt4 import QtCore, QtGui
class PbWidget(QtGui.QProgressBar):
def __init__(self, parent=None, total=20):
super(PbWidget, self).__init__()
self.setMinimum(1)
self.setMaximum(total)
self._active = False
def update_bar(self, to_add_number):
while True:
time.sleep(0.01)
value = self.value() + to_add_number
self.setValue(value)
QtGui.qApp.processEvents()
if (not self._active or value >= self.maximum()):
break
self._active = False
def closeEvent(self, event):
self._active = False
class MainWindow(QtGui.QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
self.main_layout = QtGui.QVBoxLayout()
self.pb=PbWidget(total=101)
self.main_layout.addWidget(self.pb)
ok_button = QtGui.QPushButton("Press to update Progress Bar")
ok_button.clicked.connect(self.OK)
self.main_layout.addWidget(ok_button)
central_widget = QtGui.QWidget()
central_widget.setLayout(self.main_layout)
self.setCentralWidget(central_widget)
def OK(self):
self.pb.update_bar(10)
if __name__ == '__main__':
import sys
app = QtGui.QApplication(sys.argv)
window = MainWindow()
window.resize(480, 320)
window.show()
sys.exit(app.exec_())
Yes, use CSS
for that. Yes CSS
you have readed well! ;)
add this function to your PbWidget
class:
def change_color(self, color):
template_css = """QProgressBar::chunk { background: %s; }"""
css = template_css % color
self.setStyleSheet(css)
the color parameter expects something like: "yellow", "blue", "red" ... and also HEX notation: "#FFD45", etc ...
You can call this function inside update_bar
and pass to it some color depending on the progress bar value. For example:
def update_bar(self, to_add_number):
while True:
time.sleep(0.5)
value = self.value() + to_add_number
self.setValue(value)
if value > 50:
self.change_color("yellow")
QtGui.qApp.processEvents()
if (value >= self.maximum()):
break
self._active = False
For changing others visual properties, visit: Qt StyleSheet Reference and look for QtProgressBar
. Good luck!!!