帮我写一个自定义QScrollArea,可以实现鼠标拖动
时间: 2024-03-27 17:40:25 浏览: 53
好的,下面是一个自定义的 `DraggableScrollArea` 类,它继承自 `QScrollArea`,并实现了鼠标拖动功能:
```c++
#include <QMouseEvent>
#include <QScrollBar>
#include <QScrollArea>
class DraggableScrollArea : public QScrollArea
{
public:
DraggableScrollArea(QWidget *parent = nullptr) : QScrollArea(parent), m_lastPos(QPoint(-1, -1)) {}
protected:
void mousePressEvent(QMouseEvent *event) override
{
if (event->button() == Qt::LeftButton) {
m_lastPos = event->pos();
event->accept();
} else {
QScrollArea::mousePressEvent(event);
}
}
void mouseMoveEvent(QMouseEvent *event) override
{
if (event->buttons() & Qt::LeftButton && m_lastPos != QPoint(-1, -1)) {
QPoint delta = event->pos() - m_lastPos;
m_lastPos = event->pos();
horizontalScrollBar()->setValue(horizontalScrollBar()->value() - delta.x());
verticalScrollBar()->setValue(verticalScrollBar()->value() - delta.y());
event->accept();
} else {
QScrollArea::mouseMoveEvent(event);
}
}
void mouseReleaseEvent(QMouseEvent *event) override
{
if (event->button() == Qt::LeftButton) {
m_lastPos = QPoint(-1, -1);
event->accept();
} else {
QScrollArea::mouseReleaseEvent(event);
}
}
private:
QPoint m_lastPos;
};
```
这个自定义的 `DraggableScrollArea` 类重写了鼠标按下、鼠标移动和鼠标释放事件,捕获并处理鼠标拖动事件,实现了鼠标拖动功能。你可以像使用普通的 `QScrollArea` 一样使用这个类,只需要将 `QScrollArea` 替换为 `DraggableScrollArea` 即可。
阅读全文