效果如下:

关键代码:
Dialog对象:
.h
protected:
void paintEvent(QPaintEvent *event);
private:
QTimer *timer;
int angle;
.cpp
#include<QtMath>
#include<cmath>
Dialog::Dialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::Dialog)
{
ui->setupUi(this);
angle=0;
timer=new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(update()));
timer->start(200);
}
Dialog::~Dialog()
{
delete ui;
}
void Dialog::paintEvent(QPaintEvent *event)
{
QPainter painter(this);
angle=(angle+10)%360;
QRect rect(100,100,200,200);
qreal centerRadius = 200*qSqrt(2);
QPoint startPoint(200, 200);
QPoint endPoint(centerRadius*qCos(M_PI*(45+angle)/180), centerRadius*qSin(M_PI*(45+angle)/180));
QPoint offsetPoint=startPoint - endPoint;
// 虽然是先定义的translate, 然后rotate,但是实际上是先绕着(0,0)旋转, 然后+offsetPoint最后还是startPoint.
painter.translate(offsetPoint);
painter.rotate(angle);
painter.drawImage(rect, QImage(":/images/images/OIP.jfif"));
}
本文介绍了一个使用Qt实现的图像定时旋转效果。通过继承QDialog并利用QTimer触发paintEvent,每次更新角度并重新绘制图像,实现了图像的平滑旋转。文章详细展示了如何在paintEvent中使用translate和rotate方法,结合数学计算确定旋转中心和角度,以及如何加载和显示图像。

1530

被折叠的 条评论
为什么被折叠?



