zl程序教程

您现在的位置是:首页 >  工具

当前栏目

Qt 显示gif

Qt 显示 gif
2023-09-11 14:22:56 时间

开发环境 Qt5.5.1、Qt Creator 3.5.1 

Qt 与 Android 一样,如果把gif当做普通图片加载的话有且仅会显示图片的第一帧。

因此我实现了一个自定义控件,既可以加载动态的gif,也可以加载普通的图片

(1)mygifwidget.h

#ifndef MYGIFWIDGET_H
#define MYGIFWIDGET_H
 
#include <QLabel>
#include <QMovie>
#include <QPalette>
#include <QBrush>
#include <QResizeEvent>
#include <QPaintEvent>
#include <QPainter>
 
class MyGifWidget : public QLabel
{
    Q_OBJECT
public:
    explicit MyGifWidget(QWidget *parent = 0);
    ~MyGifWidget();
    void resizeEvent(QResizeEvent* e);
    void paintEvent(QPaintEvent* e);
    bool setPath(QString path);
    bool setGif(QString path);
    bool setImage(QString path);
    void stop();
private:
    QMovie* movie;
    QPixmap* pixmap;
    bool setImage(QPixmap* pixmap);
};
 
#endif // MYGIFWIDGET_H

(2)mygifwidget.cpp

#include "mygifwidget.h"
 
MyGifWidget::MyGifWidget(QWidget *parent) : QLabel(parent) {
    this->setAutoFillBackground(true);
    movie = NULL;
    pixmap = NULL;
}
 
MyGifWidget::~MyGifWidget() {
    if(movie != NULL) delete movie;
    if(pixmap != NULL) delete pixmap;
}
 
void MyGifWidget::resizeEvent(QResizeEvent *e) {
    if(isHidden()) {
        return;
    }
    if(movie != NULL && movie->isValid()) {
        movie->setScaledSize(e->size());
    } else if(pixmap != NULL && !pixmap->isNull()) {
        pixmap->scaled(e->size());
    }
}
 
void MyGifWidget::paintEvent(QPaintEvent *e) {
    if(!isVisible()) {
        return;
    }
    if(pixmap != NULL && !pixmap->isNull()) {
        QPainter* painter = new QPainter(this);
        painter->drawPixmap(e->rect(), *pixmap);
        delete painter;
    } else {
        QLabel::paintEvent(e);
    }
}
 
bool MyGifWidget::setPath(QString path) {
    if(path.isEmpty()) {
        return false;
    }
    if(path.toLower().endsWith(".gif")) {
        return setGif(path);
    } else {
        return setImage(path);
    }
}
 
bool MyGifWidget::setGif(QString path) {
    stop();
    movie = new QMovie(path);
    bool result = movie->isValid();
    if(result) {
        movie->setScaledSize(this->size());
        this->setMovie(movie);
        movie->start();
    }
    return result;
}
 
bool MyGifWidget::setImage(QString path) {
    stop();
    pixmap = new QPixmap(path);
    return setImage(pixmap);
}
 
bool MyGifWidget::setImage(QPixmap* pixmap) {
    if(!pixmap->isNull()) {
        QPalette* palette = new QPalette();
        pixmap->scaled(this->size());
        palette->setBrush(QPalette::Window, QBrush(*pixmap));
        setPalette(*palette);
        delete palette;
        return true;
    }
    return false;
}
 
void MyGifWidget::stop() {
    if(movie != NULL) {
        movie->stop();
        delete movie;
        movie = NULL;
    }
    if(pixmap != NULL){
        delete pixmap;
        pixmap = NULL;
    }
}