Qt 鼠标点击自定义标题栏可拖动
在实际应用中,常常会隐藏掉Qt自带的标题栏,导致窗口无法拖动,需要自己添加鼠标事件,达到窗口拖动效果,但又不想鼠标点击整个窗口的任意位置都可拖动,所以只需要设计鼠标点击自定义的标题栏时可拖动即可。
具体步骤:
1.定义一个用来接收鼠标位置的坐标
//.h
static QPoint last;
//.cpp
//类外初始化
QPoint Tip::last(0,0);
2.自定义标题栏高度
#define WIN_TITLE_HEIGHT 30
3.实现鼠标事件
//鼠标按下
void mousePressEvent(QMouseEvent* event);
//鼠标移动
void mouseMoveEvent(QMouseEvent* event);
//鼠标释放
void mouseReleaseEvent(QMouseEvent* event);
通过鼠标点击事件,判断鼠标是否在标题栏,如果是,则获取当前位置;鼠标移动事件实时改变窗口位置
void Tip::mousePressEvent(QMouseEvent *event)//判断鼠标点击时是否小于标题栏高度
{
if(event->y()<TITLE_HEIGHT)
{
last = event->globalPos();//获取坐标
}
}
void Tip::mouseMoveEvent(QMouseEvent *event)//鼠标移动,实时修改窗口的坐标
{
if(event->y()<TITLE_HEIGHT)
{
int dx = event->globalX() - last.x();
int dy = event->globalY() - last.y();
last = event->globalPos();
this->move(this->x()+dx,this->y()+dy);
}
}
void Tip::mouseReleaseEvent(QMouseEvent *event)//鼠标释放
{
if(event->y()<TITLE_HEIGHT)
{
int dx = event->globalX() - last.x();
int dy = event->globalY() - last.y();
this->move(this->x()+dx,this->y()+dy);
}
}
完整代码
tip.h
public:
static QPoint last;
//鼠标按下
void mousePressEvent(QMouseEvent* event);
//鼠标移动
void mouseMoveEvent(QMouseEvent* event);
//鼠标释放
void mouseReleaseEvent(QMouseEvent* event);
tip.cpp
#include "tip.h"
#include "ui_tip.h"
#include <QMouseEvent>
#define WIN_TITLE_HEIGHT 30
QPoint Tip::last(0,0);
Tip::Tip(QWidget *parent) :
QDialog (parent),
ui(new Ui::Tip)
{
ui->setupUi(this);
}
Tip::~Tip()
{
delete ui;
}
void Tip::on_toolButton_clicked()
{
close();
}
void Tip::mousePressEvent(QMouseEvent *event)//判断鼠标点击时是否小于标题栏高度
{
if(event->y()<TITLE_HEIGHT)
{
last = event->globalPos();//获取坐标
}
}
void Tip::mouseMoveEvent(QMouseEvent *event)//鼠标移动,实时修改窗口的坐标
{
if(event->y()<TITLE_HEIGHT)
{
int dx = event->globalX() - last.x();
int dy = event->globalY() - last.y();
last = event->globalPos();
this->move(this->x()+dx,this->y()+dy);
}
}
void Tip::mouseReleaseEvent(QMouseEvent *event)//鼠标释放
{
if(event->y()<TITLE_HEIGHT)
{
int dx = event->globalX() - last.x();
int dy = event->globalY() - last.y();
this->move(this->x()+dx,this->y()+dy);
}
}
版权声明:本文为love_dear原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。