|
发表于 2024-2-21 13:01:36
|
显示全部楼层
没关系,让我帮你具体代入一下吧。以下是完整的代码示例:
- import sys
- from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout
- from PyQt5.QtGui import QPainter, QColor, QPen
- from PyQt5.QtCore import QTimer
- class CustomProgressBar(QWidget):
- def __init__(self, parent=None):
- super().__init__(parent)
- self.setMinimumSize(200, 30)
- self.value = 0
-
- def paintEvent(self, event):
- painter = QPainter(self)
- painter.setRenderHint(QPainter.Antialiasing)
-
- # 绘制背景
- bgRect = self.rect()
- bgRect.adjust(1, 1, -1, -1)
- painter.fillRect(bgRect, QColor(240, 240, 240))
-
- # 绘制进度条
- progressRect = bgRect
- progressRect.setWidth(progressRect.width() * self.value / 100)
- painter.fillRect(progressRect, QColor(0, 120, 230))
-
- # 绘制边框
- pen = QPen(QColor(200, 200, 200))
- pen.setWidth(2)
- painter.setPen(pen)
- painter.drawRect(bgRect)
-
- def setValue(self, value):
- self.value = value
- self.update()
-
- def scrollToCenter(self):
- self.setValue(50)
-
- def startAnimation(self):
- self.timer = QTimer(self)
- self.timer.timeout.connect(self._animate)
- self.timer.start(100)
-
- def _animate(self):
- self.value += 5
- if self.value > 100:
- self.value = self.value % 100
- self.update()
- class MainWindow(QWidget):
- def __init__(self):
- super().__init__()
- self.initUI()
-
- def initUI(self):
- layout = QVBoxLayout(self)
-
- progressBar = CustomProgressBar()
- layout.addWidget(progressBar)
-
- progressBar.scrollToCenter()
- progressBar.startAnimation()
-
- self.setLayout(layout)
- self.show()
- if __name__ == "__main__":
- app = QApplication(sys.argv)
- mainWindow = MainWindow()
- sys.exit(app.exec_())
复制代码
将以上代码保存为一个Python文件(如"main.py"),然后运行该文件,你将看到一个带有自定义样式的进度条控件,并且进度条的滚动会自动滚动到中间,同时进度条也会自动动画效果地更新。
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。 |
|