工作中遇到了这样的问题,有一个等待的图片,UI只给了一个静态的切图,需要我自己去做旋转效果,以下的代码参考了weixin_小栓的文章QT PC 使用QLabel实现circle图片显示和图片旋转动画的功能以及ChatGpt的总结
效果图
头文件.h
#ifndef CLABELROTATE_H
#define CLABELROTATE_H
#include <QWidget>
#include <QLabel>
#include <QTimer>
#include <QPushButton>
#include <QVBoxLayout>
class CLabelRotate : public QWidget {
Q_OBJECT
public:
explicit CLabelRotate(const QPixmap &pixmap, QWidget *parent = nullptr);
public slots:
void Rotate(); //开始旋转
void ToggleRotation(); // 切换图片旋转状态
void SetRotation(int rotation);
private:
QLabel *m_rotatingLabel;
QPushButton *m_button;
QTimer *m_timer;
int m_rotation;
QPixmap m_pixmapOrigin;
};
#endif // CLABELROTATE_H
.cpp
#include "CLabelRotate.h"
#include <QPainter>
#include <QVBoxLayout>
CLabelRotate::CLabelRotate(const QPixmap &pixmap, QWidget *parent)
: QWidget(parent), m_rotation(0), m_pixmapOrigin(pixmap)
{
this->setStyleSheet("background-color:black;");
m_rotatingLabel = new QLabel(this);
m_rotatingLabel->setFixedSize(200, 200); // 设置旋转的 QLabel 大小为 200*200
m_button = new QPushButton("Toggle Rotation", this); // 创建按钮,用于切换图片旋转状态
connect(m_button, &QPushButton::clicked, this, &CLabelRotate::ToggleRotation); // 按钮点击事件,开始旋转图片
m_button->setStyleSheet("background-color:#17A1FF;color:#FFFFFF");
m_timer = new QTimer(this);
connect(m_timer, &QTimer::timeout, this, &CLabelRotate::Rotate); // 定时器超时事件,定时旋转图片
m_timer->start(10); // 每10毫秒旋转一次图片
QVBoxLayout *layout = new QVBoxLayout(this); // 垂直布局
layout->addWidget(m_rotatingLabel); // 将 QLabel 添加到布局中
layout->addWidget(m_button); // 将按钮添加到布局中
this->setLayout(layout);
}
void CLabelRotate::Rotate()
{
m_rotation += 10;
setRotation(m_rotation);
}
void CLabelRotate::ToggleRotation()
{
if (m_timer->isActive()) {
m_timer->stop(); // 停止定时器,停止旋转图片
} else {
m_timer->start(10); // 启动定时器,开始旋转图片
}
}
void CLabelRotate::setRotation(int rotation)
{
m_rotation = rotation;
// 使用 QPainter 进行旋转
int imageWidth = m_pixmapOrigin.width();
int imageHeight = m_pixmapOrigin.height();
QPixmap temp(m_pixmapOrigin.size());
temp.fill(Qt::transparent);
QPainter painter(&temp);
painter.setRenderHint(QPainter::SmoothPixmapTransform, true);
painter.translate(imageWidth / 2, imageHeight / 2);
painter.rotate(m_rotation);
painter.translate(-(imageWidth / 2), -(imageHeight / 2));
painter.drawPixmap(0, 0, m_pixmapOrigin);
painter.end();
m_rotatingLabel->setPixmap(temp); // 将旋转后的 QPixmap 设置为 QLabel 的显示内容
}
main
#include <QApplication>
#include "CLabelRotate.h"
int main(int argc, char *argv[]) {
QApplication app(argc, argv);
QPixmap pixmap(":/path/to/your/image.png"); // 替换为实际图片路径
CLabelRotate item(pixmap);
item.show();
return app.exec();
}