求Qt中加载图片并实现沿x轴平移动画的简单示例
Qt 图片沿X轴平移动画最简实现方案
以下两种实现均无需自定义绘图逻辑,直接加载图片文件即可实现平移动画,适配轻量使用场景:
QML 实现(推荐,代码量最少)
直接使用Image组件加载图片,配合PropertyAnimation控制X轴位置即可:
import QtQuick 2.15 import QtQuick.Window 2.15 Window { width: 640 height: 480 visible: true title: qsTr("图片平移动画") Image { id: targetImg source: "qrc:/test_image.png" // 替换为你的图片资源路径 x: 0 // 初始X轴位置 y: 150 // Y轴位置固定即可 } // X轴平移动画配置 PropertyAnimation { id: xMoveAni target: targetImg property: "x" to: 450 // X轴平移终点 duration: 1200 // 动画时长,单位毫秒 easing.type: Easing.InOutSine // 可选缓动效果,不需要可删除 running: true // 开启动画自动运行,不需要可删除,手动调用start()触发 loops: Animation.Infinite // 可选无限循环,不需要可删除 } }
Qt Widgets 实现
使用QLabel加载图片,配合QPropertyAnimation控制位置即可:
核心代码示例
// 头文件中声明成员变量 #include <QLabel> #include <QPropertyAnimation> class MainWindow : public QMainWindow { // ... 其他基类代码 private: QLabel *imgLabel; QPropertyAnimation *xAnim; }; // 构造函数中初始化逻辑 MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) { resize(640, 480); // 初始化图片显示控件 imgLabel = new QLabel(this); imgLabel->setPixmap(QPixmap(":/test_image.png")); // 替换为你的图片资源路径 imgLabel->move(0, 150); // 初始位置 imgLabel->adjustSize(); // 自适应图片大小 // 初始化动画 xAnim = new QPropertyAnimation(imgLabel, "pos"); xAnim->setStartValue(QPoint(0, 150)); // 起始位置,Y轴固定为150 xAnim->setEndValue(QPoint(450, 150)); // 终点位置,仅修改X轴值 xAnim->setDuration(1200); // 动画时长 // 启动动画,也可以绑定到按钮点击等事件触发 xAnim->start(); }
额外配置说明
- 如需循环播放,调用
xAnim->setLoopCount(-1)即可 - 如需加缓动效果,调用
xAnim->setEasingCurve(QEasingCurve::InOutSine)即可
内容的提问来源于stack exchange,提问作者SomeUserNameForThisWebsite
相关产品推荐
相关产品推荐

