其他推荐内容:
- qt电池控件设计:https://blog.csdn.net/weixin_42887343/article/details/113932145
- QWidget控件拖动:https://blog.csdn.net/weixin_42887343/article/details/114384324
- QWidget控件旋转方法:https://blog.csdn.net/weixin_42887343/article/details/115037420
- qt柱状图控件设计:https://blog.csdn.net/weixin_42887343/article/details/115124178
- qt淡化提示框设计:https://blog.csdn.net/weixin_42887343/article/details/109303972
- qt之led(点阵)控件类设计:https://blog.csdn.net/weixin_42887343/article/details/115348953
说明:使用该类,可实现任意QWidget子类控件如下图移动。
效果:

h文件:
#ifndef MOVEWIDGET_H
#define MOVEWIDGET_H
#include <QWidget>
class MoveWidget : public QObject
{
Q_OBJECT
public:
explicit MoveWidget(QObject *parent = 0);
public Q_SLOTS:
void setLeftButton(bool leftButton); //设置是否限定鼠标左键
void setInControl(bool inControl); //设置是否限定不能移出容器外面
void setWidget(QWidget *widget); //设置要移动的控件
protected:
bool eventFilter(QObject *watched, QEvent *event);
private:
QWidget *widget; //移动的控件
QPoint lastPoint; //最后按下的坐标
bool pressed; //鼠标是否按下
bool leftButton; //限定鼠标左键
bool inControl; //限定在容器内
};
#endif // MOVEWIDGET_H
cpp文件:
#include "movewidget.h"
#include "qevent.h"
#include "qdebug.h"
MoveWidget::MoveWidget(QObject *parent) :
QObject(parent)
,lastPoint(QPoint(0, 0))
,pressed(false)
,leftButton(true)
,inControl(true)
,widget(false)
{
}
bool MoveWidget::eventFilter(QObject *watched, QEvent *event)
{
if (widget != 0 && watched == widget)
{
QMouseEvent *mouseEvent = (QMouseEvent *)event;
if (mouseEvent->type() == QEvent::MouseButtonPress)
{
//如果限定了只能鼠标左键拖动则判断当前是否是鼠标左键
if (leftButton && mouseEvent->button() != Qt::LeftButton)
return false;
//判断控件的区域是否包含了当前鼠标的坐标
if (widget->rect().contains(mouseEvent->pos()))
{
lastPoint = mouseEvent->pos();
pressed = true;
}
}
else if (mouseEvent->type() == QEvent::MouseMove && pressed)
{
//计算坐标偏移值,调用move函数移动过去
int offsetX = mouseEvent->pos().x() - lastPoint.x();
int offsetY = mouseEvent->pos().y() - lastPoint.y();
int x = widget->x() + offsetX;
int y = widget->y() + offsetY;
if (inControl)
{
//可以自行调整限定在容器中的范围,这里默认保留20个像素在里面
int offset = 20;
bool xyOut = (x + widget->width() < offset || y + widget->height() < offset);
bool whOut = false;
QWidget *w = (QWidget *)widget->parent();
if (w != 0)
whOut = (w->width() - x < offset || w->height() - y < offset);
if (xyOut || whOut)
return false;
}
widget->move(x, y);
}
else if (mouseEvent->type() == QEvent::MouseButtonRelease && pressed)
pressed = false;
}
return QObject::eventFilter(watched, event);
}
void MoveWidget::setWidget(QWidget *widget)
{
if (this->widget == 0)
{
this->widget = widget;
this->widget->installEventFilter(this);
}
}
void MoveWidget::setLeftButton(bool leftButton)
{
this->leftButton = leftButton;
}
void MoveWidget::setInControl(bool inControl)
{
this->inControl = inControl;
}
使用方法:
设置
ui->pushButton
、
ui->pushButton_2
按钮可移动,参数可以是任意
QWidget
子类。
MoveWidget *move = new MoveWidget(this);
move->setWidget(ui->pushButton);
MoveWidget *move2 = new MoveWidget(this);
move2->setWidget(ui->pushButton_2);