QT之滑动切换UI框架

简介

使用QT制作一个UI图片切换框架。
思路:主要通过移动像素坐标差值来判断方向,左上角坐标为(0,0),右加左减,松开减去按压时的横坐标大于0则右移,否则左移。

代码展示

#define X_Threshold_Direction          4       //X方向移动量
#define Y_Threshold_Direction          40      //Y方向移动量

添加点击事件

this->installEventFilter(this);     //设置点击事件

点击事件实现

bool MainWindow::eventFilter(QObject *watch, QEvent *evn)
{
    static int press_x_value;     //点击时屏幕的横坐标
    static int press_y_value;     //点击时屏幕的纵坐标
    static int relea_x_value;     //松开时屏幕的横坐标
    static int relea_y_value;     //松开时屏幕的纵坐标

    QMouseEvent *event = static_cast<QMouseEvent *>(evn);
    //获取点击鼠标(手指)时的坐标
    if (event->type() == QEvent::MouseButtonPress)
    {
        press_x_value = event->globalX();
        press_y_value = event->globalY();
    }
    //获取松开鼠标(手指)时的坐标
    if(event->type() == QEvent::MouseButtonRelease)
    {
        relea_x_value = event->globalX();
        relea_y_value = event->globalY();
    }
    //对鼠标(手指)滑动的方向进行判断(右滑)
    if((relea_x_value - press_x_value) > X_Threshold_Direction && event->type() == QEvent::MouseButtonRelease && qAbs(relea_y_value - press_y_value) < Y_Threshold_Direction)
    {
        if (index == 4)
        {
            index = 1;
        }
        else
        {
            index++;
        }
        this->setStyleSheet(QString("border-image: url(:/image/%1.jpg);").arg(index));        //切换图片
        qDebug() << "right move";
    }
    //对鼠标(手指)滑动的方向进行判断(左滑)
    if((press_x_value - relea_x_value) > X_Threshold_Direction && event->type() == QEvent::MouseButtonRelease && qAbs(relea_y_value - press_y_value) < Y_Threshold_Direction)
    {
        if(index == 1)
        {
            index = 4;
        }
        else
        {
            index--;
        }
        this->setStyleSheet(QString("border-image: url(:/image/%1.jpg);").arg(index));        //切换图片
        qDebug() << "left move";
    }

    return QWidget::eventFilter(watch, evn);
}

效果如下

video

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

路过的小熊~

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值