- 创建一个Qt GUI项目。
- 在主窗口中添加一个QLabel控件,并设置其初始位置和大小,同时在属性编辑器中勾选“ScaledContents”以保证图像按比例缩放并填充整个控件。
- 在主窗口的构造函数中创建一个QTimer对象,并将其连接到槽函数onTimer()。这个定时器用于定时更新图像的位置,从而实现滑动效果。
- 在onTimer()槽函数中更新QLabel控件的位置。可以使用QPropertyAnimation类来实现平滑地移动图像。
- 编写启动和停止动画的槽函数startAnimation()和stopAnimation(),分别启动和停止定时器,并根据需要设置图像的起始位置、终止位置、移动时间等参数。
- 运行程序,单击“开始”按钮启动动画效果。可以通过调整参数来改变滑动速度和方向。
以下是示例代码:
mainwindow.h:
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#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 slots:
void onTimer();
void startAnimation();
void stopAnimation();
private:
Ui::MainWindow *ui;
QTimer *m_timer;
QPropertyAnimation *m_animation;
};
#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);
// 创建定时器并连接到槽函数
m_timer = new QTimer(this);
connect(m_timer, &QTimer::timeout, this, &MainWindow::onTimer);
// 创建动画对象
m_animation = new QPropertyAnimation(ui->label, "pos", this);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::onTimer()
{
// 更新图像位置
QPoint pos = ui->label->pos();
pos.setX(pos.x() - 1);
if (pos.x() < -ui->label->width()) {
pos.setX(width());
}
ui->label->move(pos);
}
void MainWindow::startAnimation()
{
// 设置动画参数
m_animation->setDuration(2000); // 2秒钟移动完整个窗口宽度
m_animation->setStartValue(QPoint(width(), 100)); // 起始位置在窗口右侧,纵坐标为100像素
m_animation->setEndValue(QPoint(-ui->label->width(), 100)); // 终止位置在控件左侧,纵坐标为100像素
// m_animation->setEasingCurve(QEasingCurve::InOutQuad); // 设置缓动函数(可选)
// 启动动画和定时器
// m_animation->start();
// m_timer->start(20); // 每隔20毫秒更新一次
QGraphicsOpacityEffect *eff = new QGraphicsOpacityEffect(this);
ui->label->setGraphicsEffect(eff);
QPropertyAnimation *a = new QPropertyAnimation(eff, "opacity");
a->setDuration(3000);
a->setStartValue(1);
a->setEndValue(0);
connect(a, &QPropertyAnimation::finished, this, [=](){
qDebug() << "animation finished";
delete a;
});
connect(m_timer, &QTimer::timeout, this, [=]() {
qDebug() << "timer timeout";
if (ui->label->pos().x() < -ui->label->width()) {
m_animation->stop();
m_timer->stop();
a->start(QAbstractAnimation::DeleteWhenStopped); // 启动透明度动画
}
});
m_animation->start();
m_timer->start(20); // 每隔20毫秒更新一次
}
void MainWindow::stopAnimation()
{
// 停止动画和定时器
// m_animation->stop();
// m_timer->stop();
}
main.cpp:
#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
在主窗口的UI设计器中添加一个“开始”按钮和一个“停止”按钮,并将它们分别连接到startAnimation()和stopAnimation()槽函数。运行程序,单击“开始”按钮即可看到图像滑动效果。