Qt事件重写实现按住左键拖动移动控件
1. 遇到的问题:我们需要在一个界面中实现控件(如按钮,标签等)的拖动,怎么办呢?
如下图所示,我这个控件实际上是一个QWidget,类继承如下
class DeviceButton : public QWidget
2. 很简单:只需要在需要实现的控件类中重写eventFilter
即可
bool eventFilter(QObject *watched, QEvent *event)
,如下图所示,override
是重写覆盖的意思,意思是重写父类的虚函数,可起到提示的作用,如果不添加,自己写函数名的时候写错一个字母了,这个函数就变成自己写的函数了,不调用就不会触发,添加了override
就不一样了,如果写错了要重写父类的虚函数名,就会报错,可以起到提示的作用,也可以让自己或别人更清楚的知道,这个函数是重写的,不是自己写的
3. 重写的代码如下(通用的)
bool DeviceButton::eventFilter(QObject *watched, QEvent *event)
{
static QPoint lastPoint;
static bool isPressed = false;
if (event->type() == QEvent::MouseButtonPress) {
QMouseEvent *e = static_cast<QMouseEvent *>(event);
if (this->rect().contains(e->pos()) && (e->button() == Qt::LeftButton)) {
lastPoint = e->pos();
isPressed = true;
}
} else if (event->type() == QEvent::MouseMove && isPressed) {
QMouseEvent *e = static_cast<QMouseEvent *>(event);
int dx = e->pos().x() - lastPoint.x();
int dy = e->pos().y() - lastPoint.y();
this->move(this->x() + dx, this->y() + dy);
return true;
} else if (event->type() == QEvent::MouseButtonRelease && isPressed) {
isPressed = false;
}
if (event->type() == QEvent::MouseButtonPress) {
emit clicked();
} else if (event->type() == QEvent::MouseButtonDblClick) {
emit doubleClicked();
}
return QWidget::eventFilter(watched, event);
}
添加之后,发现可以拖动了