我要问的是,达到100%时是否有更优雅的方法来更改QProgessBar
的条形颜色。在下面的Python代码中,我使用了2 QPalette
。背景颜色和条形颜色的default_palette
低于100%,达到100%时的green_palette
。
main.py
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow
from PyQt5.uic import loadUi
from PyQt5.QtGui import QPalette
from PyQt5.QtCore import Qt
class MainWindow(QMainWindow):
def __init__(self, parent=None):
super().__init__(parent)
loadUi("mainwindow.ui", self)
self.default_palette = QPalette(self.palette())
self.default_palette.setColor(QPalette.Highlight, Qt.blue)
self.default_palette.setColor(QPalette.Base, Qt.red)
self.green_palette = QPalette(self.palette())
self.green_palette.setColor(QPalette.Highlight, Qt.green)
self.progressBar.setPalette(self.default_palette)
def update_bar(self, value):
self.progressBar.setValue(value)
if value >= 100:
self.progressBar.setPalette(self.green_palette)
else:
self.progressBar.setPalette(self.default_palette)
def main():
app = QApplication(sys.argv)
main_window = MainWindow()
main_window.show()
main_window.horizontalSlider.valueChanged.connect(main_window.update_bar)
sys.exit(app.exec_())
if __name__ == "__main__":
main()
mainwindow.ui
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>MainWindow</class>
<widget class="QMainWindow" name="MainWindow">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>700</width>
<height>300</height>
</rect>
</property>
<property name="windowTitle">
<string>Progress Bar Colors</string>
</property>
<property name="locale">
<locale language="English" country="UnitedKingdom"/>
</property>
<widget class="QWidget" name="centralwidget">
<layout class="QGridLayout" name="gridLayout_2">
<item row="0" column="0">
<layout class="QGridLayout" name="gridLayout">
<item row="0" column="0">
<spacer name="verticalSpacer">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>20</width>
<height>40</height>
</size>
</property>
</spacer>
</item>
<item row="1" column="0">
<widget class="QProgressBar" name="progressBar">
<property name="styleSheet">
<string notr="true"/>
</property>
<property name="value">
<number>50</number>
</property>
</widget>
</item>
<item row="2" column="0">
<widget class="QSlider" name="horizontalSlider">
<property name="maximum">
<number>100</number>
</property>
<property name="value">
<number>50</number>
</property>
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
</widget>
</item>
<item row="3" column="0">
<spacer name="verticalSpacer_2">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>20</width>
<height>40</height>
</size>
</property>
</spacer>
</item>
</layout>
</item>
</layout>
</widget>
<widget class="QMenuBar" name="menubar">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>700</width>
<height>28</height>
</rect>
</property>
</widget>
<widget class="QStatusBar" name="statusbar"/>
</widget>
<resources/>
<connections/>
</ui>