这是一个基于Qt的圆环形进度条的示例代码:

#include <QPainter>
#include <QPropertyAnimation>
#include <QSequentialAnimationGroup>
#include <QWidget>

class CountdownWidget : public QWidget {
  Q_OBJECT

 public:
  explicit CountdownWidget(QWidget* parent = nullptr)
      : QWidget(parent), m_progress(0.0) {}

  void setDuration(int duration) { m_duration = duration; }

  void start() {
    m_progress = 0.0;

    QPropertyAnimation* animation =
        new QPropertyAnimation(this, "progress");
    animation->setDuration(m_duration * 1000);
    animation->setStartValue(0.0);
    animation->setEndValue(1.0);
    connect(animation, SIGNAL(finished()), this, SIGNAL(completed()));

    QSequentialAnimationGroup* group = new QSequentialAnimationGroup;
    group->addAnimation(animation);

    group->start();
  }

 signals:
  void completed();

 protected:
  void paintEvent(QPaintEvent* event) override {
    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing, true);

    int side = qMin(width(), height());
    int x = (width() - side) / 2;
    int y = (height() - side) / 2;

    QRectF rect(x, y, side, side);

    painter.setPen(Qt::NoPen);
    painter.setBrush(QColor(255, 255, 255, 128));
    painter.drawEllipse(rect);

    painter.setBrush(QColor(255, 0, 0, 128));
    painter.drawPie(rect, 90 * 16, -m_progress * 360 * 16);
  }

  Q_PROPERTY(qreal progress READ progress WRITE setProgress NOTIFY progressChanged)

 public:
  qreal progress() const { return m_progress; }

 public slots:
  void setProgress(qreal progress) {
    if (m_progress == progress) return;

    m_progress = progress;
    emit progressChanged(progress);

    update();
  }

 private:
  int m_duration;
  qreal m_progress;
};

使用方法:

CountdownWidget* countdownWidget = new CountdownWidget(this);
countdownWidget->setDuration(10);
countdownWidget->start();
connect(countdownWidget, SIGNAL(completed()), this, SLOT(onCountdownCompleted()));

其中,setDuration用于设置倒计时的时长(单位:秒),start用于开始倒计时,completed信号在倒计时结束后发出。

Qt倒计时圆环形进度器

原文地址: https://www.cveoy.top/t/topic/byVv 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录