Qt QWidget实现图片旋转动画
作者:小灰灰搞电子
这篇文章主要为大家详细介绍了如何使用了Qt和QWidget实现图片旋转动画效果,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下
一、效果展示

二、源码分享
本例程通过QGraphicsView实现svg格式图片旋转。

.hpp
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QGraphicsSvgItem>
#include <QGraphicsScene>
#include <QTimer>
#include <QPropertyAnimation>
QT_BEGIN_NAMESPACE
namespace Ui {
class MainWindow;
}
QT_END_NAMESPACE
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
private:
Ui::MainWindow *ui;
QGraphicsSvgItem *graphItem;
QGraphicsScene *graphScene;
};
#endif // MAINWINDOW_H
.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
this->graphScene = new QGraphicsScene();
this->ui->graphicsView->setScene(this->graphScene);
this->graphItem = new QGraphicsSvgItem( ":/image/running.svg" );
this->graphItem->setScale(0.5);
QRectF boundingRect = this->graphItem->boundingRect();
this->graphItem->setTransformOriginPoint(boundingRect.width() / 2, boundingRect.height() / 2);
graphScene->addItem( this->graphItem );
this->graphItem->setRotation(45);
// 创建一个QPropertyAnimation对象来控制旋转属性
QPropertyAnimation* rotationAnimation = new QPropertyAnimation(this->graphItem, "rotation");
// 设置动画的起始值和结束值
rotationAnimation->setStartValue(0);
rotationAnimation->setEndValue(360);
// 设置动画持续时间(以毫秒为单位)
rotationAnimation->setDuration(3000);
// 设置动画循环次数(-1表示无限循环)
rotationAnimation->setLoopCount(-1);
// 启动动画
rotationAnimation->start();
this->ui->graphicsView->installEventFilter(this);
this->ui->graphicsView->centerOn(this->graphItem);
}
MainWindow::~MainWindow()
{
delete ui;
}
以上就是Qt QWidget实现图片旋转动画的详细内容,更多关于Qt QWidget旋转的资料请关注脚本之家其它相关文章!
