创建自定义类,实现在滚动区域内拖动鼠标显示滚动条,否则不显示滚动条。
头文件
#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);
}