首页 > 技术知识 > 正文

Qt图片旋转

开发过程中突然遇到有个按钮图标需要旋转的需求,就找了下实现旋转的实现方法,以下是实现的代码。 这里我继承了QAbstractButton类,重新绘制按钮的图片,在需要旋转的时候旋转

class spinButton : public QAbstractButton{ Q_OBJECT public: spinButton(QWidget *parent = nullptr); void setIcons(QIcon ic); void start(); void stop(); signals: public slots: void timeOut(); protected: virtual void paintEvent(QPaintEvent *e); private: QPixmap Icon; int angle = 0; bool isRotate = false; QTimer *timer = nullptr; }; TreeWidgetEx::spinButton::spinButton(QWidget *parent) : QAbstractButton(parent) { Icon = QPixmap(); timer = new QTimer(this); connect(tim,SIGNAL(timeout()),this,SLOT(timeOut())); angle = 0; } void TreeWidgetEx::spinButton::setIcons(QIcon ic) { Icon = ic; } void TreeWidgetEx::spinButton::start() { angle = 0; tim->start(20); } void TreeWidgetEx::spinButton::stop() { tim->stop(); angle = 0; update(); } void TreeWidgetEx::spinButton::timeOut() { angle += 20; if(angle >= 360) angle = 0; update(); } void TreeWidgetEx::spinButton::paintEvent(QPaintEvent *e) { Q_UNUSED(e) QPainter paint(this); paint.save(); paint.setRenderHints(QPainter::Antialiasing, true); QPixmap pixmap = Icon.scaled(this->width()-10,this->height()-10,Qt::KeepAspectRatio, Qt::SmoothTransformation); paint.rotate(angle);//坐标旋转 //经分析,应使图片中心,对应原点 paint.drawPixmap(-pixmap.width()/2,-pixmap.height()/2,pixmap); paint.restore(); }
<

猜你喜欢