Implementation Breakdown
The process relies on the QMovie and QLabel classes. Include the necessary headers:
#include <QMovie>
#include <QLabel>
Prepare an animated GIF file and note its file path. It is recommended to place the GIF inside the project directory for easier path management.
Create a QMovie object and a QLabel object. Replace path with the actual file path of your GIF. Ensure forward slashes (/) are used in the path string (e.g., C:/Users/.../file.gif).
QMovie* movie = new QMovie(path);
QLabel* label = new QLabel();
Attach the movie to the label and start the animation:
label->setMovie(movie); // Assign the QMovie to the QLabel
movie->start(); // Begin playback
Configure the label's size and placement:
label->setScaledContents(true); // Scale the GIF to fit the label size
label->setGeometry(x, y, width, height); // Set position and dimensions
Replace x, y, width, and height with the desired pixel values. Example:
label->setGeometry(200, 100, 100, 100);
Final, make the label visible:
label->show();
Combined snippet:
QMovie* movie = new QMovie(path);
QLabel* label = new QLabel();
label->setMovie(movie);
movie->start();
label->setScaledContents(true);
label->setGeometry(x, y, w, h);
label->show();
Complete Code Example
main.cpp
#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QMovie>
#include <QLabel>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = nullptr);
~MainWindow();
private:
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
// Replace the path with your own GIF file location
QMovie* movie = new QMovie("C:/Users/dengbenzhong/Desktop/temp/flower.gif");
QLabel* label = new QLabel(this);
label->setMovie(movie);
movie->start();
label->setScaledContents(true);
label->setGeometry(200, 100, 100, 100);
label->show();
}
MainWindow::~MainWindow()
{
delete ui;
}
To embed the animated GIF inside the main window rather than as a separate floating widget, set the label's parent to the main window (as shown above by passing this to the QLabel constructor).
For further questions or comments, feel free to reach out.