Qt鼠标拖动ScrollArea代替鼠标滚轮操作

    因为此前有个项目做的软件要在平板上运行,屏幕不大,滚动条太细,如果加粗滚动条影响美观,滚动条太细又点不到,用户体验较差。所以做了这个鼠标拖动即可代替鼠标滚轮的功能。


dialogex.h


#ifndef DIALOGEX_H
#define DIALOGEX_H

#include 
#include 
#include 
#include 
#include 

class DialogEx : public QDialog
{
    Q_OBJECT

public:
    DialogEx(QWidget *parent = 0);
    ~DialogEx();

    void init();

    QScrollArea*    m_pScrollArea;
    QWidget*        m_pScrollWidget;
    QLabel*         m_pTipLabel;
    bool            m_bMousePressed;
    QPoint          m_PressPosition;

protected:
    void mouseMoveEvent(QMouseEvent *e) Q_DECL_OVERRIDE;
    void mousePressEvent(QMouseEvent *e) Q_DECL_OVERRIDE;
    void mouseReleaseEvent(QMouseEvent *e) Q_DECL_OVERRIDE;
};

#endif // DIALOGEX_H


dialogex.cpp


#include "dialogex.h"

DialogEx::DialogEx(QWidget *parent)
    : QDialog(parent)
    , m_pScrollArea(NULL)
    , m_pScrollWidget(NULL)
    , m_pTipLabel(NULL)
    , m_bMousePressed(false)
{
    init();
}

DialogEx::~DialogEx()
{

}

void DialogEx::init()
{
    this->setFixedSize(300, 200);

    m_pScrollArea = new QScrollArea(this);
    m_pScrollWidget = new QWidget(m_pScrollArea);
    m_pTipLabel = new QLabel("证明我移动了", m_pScrollWidget);

    m_pScrollArea->setFixedSize(this->width(), this->height());
    m_pScrollWidget->setFixedSize(this->width(), this->height() * 2);
    m_pTipLabel->adjustSize();

    m_pScrollArea->setWidget(m_pScrollWidget);
    m_pScrollArea->setAlignment(Qt::AlignCenter);
    m_pScrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);

    m_pScrollArea->move(0, 0);
    m_pScrollWidget->move(0, 0);
    m_pTipLabel->move(100, 100);
}

void DialogEx::mouseMoveEvent(QMouseEvent *e)
{
    if (!m_bMousePressed)
    {
        return;
    }

    QPoint currentPt = e->pos();

    int dist = m_PressPosition.y() - currentPt.y();

    m_pScrollArea->verticalScrollBar()->setValue(m_pScrollArea->verticalScrollBar()->value() + dist);

    m_PressPosition = currentPt;
}

void DialogEx::mousePressEvent(QMouseEvent *e)
{
    m_bMousePressed = true;

    m_PressPosition = e->pos();
}

void DialogEx::mouseReleaseEvent(QMouseEvent *e)
{
    Q_UNUSED(e);
    m_bMousePressed = false;

    m_PressPosition.setX(0);
    m_PressPosition.setY(0);
}

main.cpp

#include "dialogex.h"
#include 

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    DialogEx w;
    w.show();

    return a.exec();
}


例子中只做了竖直方向的拖动,水平方向同理


你可能感兴趣的:(Qt,Qt,鼠标拖动)