ScrollArea支持鼠标拖动

        创建自定义类,实现在滚动区域内拖动鼠标显示滚动条,否则不显示滚动条。

        头文件

#ifndef MYSCROLLAREA_H
#define MYSCROLLAREA_H

#include <QObject>
#include <QScrollArea>
#include <QPoint>

class MyScrollArea : public QScrollArea
{
    Q_OBJECT

public:
    MyScrollArea(QWidget* parent = NULL);
    ~MyScrollArea();

protected:
    bool eventFilter(QObject *obj,QEvent *evt);

private:
    bool mMoveStart;
    bool mContinuousMove;
    QPoint mMousePoint;
};

#endif // MYSCROLLAREA_H
        源文件

#include "myscrollarea.h"
#include <QMouseEvent>
#include <QScrollBar>

MyScrollArea::MyScrollArea(QWidget *parent)
    :QScrollArea(parent)     //基类
    ,mMoveStart(false)
    ,mContinuousMove(false)
    ,mMousePoint(QPoint(0,0))
{
    installEventFilter(this);
}

MyScrollArea::~MyScrollArea()
{
}

bool MyScrollArea::eventFilter(QObject *obj, QEvent *evt)
{
    if(evt->type() == QEvent::MouseMove)
    {
        QMouseEvent *me = (QMouseEvent*) evt;
        if(me->buttons() & Qt::LeftButton)
        {
            if(!mMoveStart)
            {
//                if(me->pos().y() < (horizontalScrollBar()->pos().y() + horizontalScrollBar()->height())
//                        || me->pos().x() < (verticalScrollBar()->pos().x() + verticalScrollBar()->width()) )
//                    return false;

                mMoveStart = true;
                mContinuousMove = false;
                mMousePoint = me->globalPos();
            }
            else
            {
                setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOn);//开启滚动条
                setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);

                QScrollBar *scrollBarx = horizontalScrollBar();
                QScrollBar *scrollBary = verticalScrollBar();

                QPoint p = me->globalPos();
                int offsetx = p.x() - mMousePoint.x();
                int offsety = p.y() - mMousePoint.y();
                if(!mContinuousMove && (offsetx > -10 && offsetx < 10) && (offsety > -10 && offsety < 10))
                    return false;

                mContinuousMove = true;

                scrollBarx->setValue(scrollBarx->value() - offsetx);
                scrollBary->setValue(scrollBary->value() - offsety);
                mMousePoint = p;
            }
            return true;
        }
    }
    else if(evt->type() == QEvent::MouseButtonRelease)
    {
        mMoveStart = false;
        setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);//关闭滚动条
        setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    }
    return QObject::eventFilter(obj,evt);
}



评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值