效果如下:
关键代码:
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"));
}