自定义的Qt等待界面用的控件
这个控件非常简单,就是一个圆弧在不停地转圈圈。模仿的是WPS中等待界面的效果。通过这个控件学习Qt动画的基本操作。这个控件在VS2015和Qt5.9上测试通过。下面是效果图:
上代码,头文件:
class MWait : public QWidget { Q_OBJECT public: MWait(QWidget* parent = 0); QSize sizeHint() const override; private: void setFlagPos(int where); void paintEvent(QPaintEvent *event) override; private: int atWhere; /* [0, 360) */ };
CPP文件:
MWait::MWait(QWidget* parent) : QWidget(parent) { /* 这里0°和360°边界有重叠,导致同一个角度连续播放两帧 */ /* 但好在肉眼难以分辨出这个问题 */ QVariantAnimation* ani = new QVariantAnimation(this); ani->setStartValue(0); ani->setEndValue(360); ani->setLoopCount(-1); ani->setDuration(800); connect(ani, &QVariantAnimation::valueChanged, this, [this](const QVariant& value) { setFlagPos(value.toInt()); }); ani->start(); } void MWait::setFlagPos(int where) { atWhere = where; update(); } void MWait::paintEvent(QPaintEvent *event) { QPainter painter(this); painter.setRenderHint(QPainter::Antialiasing); int d = qMin(width(), height()); int xoff = (width() - d) / 2; int yoff = (height() - d) / 2; painter.translate(xoff, yoff); painter.setBrush(Qt::NoBrush); painter.setPen(QPen(QColor(213, 213, 213), 4)); QRect rect(2, 2, d - 4, d - 4); painter.drawEllipse(rect); painter.setPen(QPen(QColor(0, 160, 243), 4, Qt::SolidLine, Qt::RoundCap)); painter.drawArc(rect, (90 - atWhere) * 16, -150 * 16); } QSize MWait::sizeHint() const { return QSize(36, 36); }