pyqt5 如何在窗口上实现圆形进度条

以下是实现的完整的代码:

import sys
from PyQt5.QtCore import Qt, QTimer
from PyQt5.QtGui import QPainter, QColor, QFont, QPen
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout


class CircularProgress(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self._percent = 0
        self._timer = QTimer(self)
        self._timer.timeout.connect(self.update_progress)
        self._timer.start(100)  # 设置更新间隔为100ms

    def set_percent(self, percent):
        self._percent = percent
        self.update()

    def update_progress(self):
        self._percent += 1
        if self._percent > 100:
            self._percent = 0
        self.update()

    def paintEvent(self, event):
        width, height = self.width(), self.height()
        side = min(width, height)
        margin = 10
        bar_width = 10

        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing)

        # 绘制圆形
        pen = QPen(QColor(200, 200, 200))
        pen.setWidth(bar_width)
        painter.setPen(pen)
        painter.drawArc(
            margin,
            margin,
            side - 2 * margin,
            side - 2 * margin,
            0,
            360 * 16,
        )

        # 绘制进度
        pen.setColor(QColor(50, 150, 250))
        painter.setPen(pen)
        # 将百分比转换为角度,并确保结果为整数
        angle = int(-self._percent * 16 * 3.6)
        painter.drawArc(
            margin,
            margin,
            side - 2 * margin,
            side - 2 * margin,
            90 * 16,
            angle,
        )

        # 绘制百分比文字
        painter.setFont(QFont('Arial', 12))
        painter.drawText(
            0,
            0,
            width,
            height,
            Qt.AlignCenter,
            f'{self._percent}%',
        )


class MainWindow(QWidget):
    def __init__(self):
        super().__init__()
        self.init_ui()

    def init_ui(self):
        self.setGeometry(100, 100, 300, 300)
        self.setWindowTitle('Circular Progress Bar')

        circular_progress = CircularProgress(self)

        layout = QVBoxLayout()
        layout.addWidget(circular_progress)
        self.setLayout(layout)


if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())

运行这个代码,你将会看到一个带有圆形进度条的窗口显示出来,进度条会以每秒钟增加1%的速度更新。

你可能感兴趣的:(python,pyqt,qt,python,开发语言,pyqt)