QT自定义标题栏窗口移动
程序员文章站
2022-03-07 16:01:25
...
设置自定义的标题栏需要修改鼠标移动事件,这样窗口才能移动。
有一点点的bug,窗口会突然移动,后续修改。
代码
.h文件
//函数
void mousePressEvent(QMouseEvent *event);
void mouseMoveEvent(QMouseEvent *event);
void mouseReleaseEvent(QMouseEvent *event);
//变量
bool mPressBool;
QPoint mouseStartPoint;
QPoint mwindowTopLeftPoint;
QDockWidget* mpDockMouse;
.cpp文件
//申请内存并隐藏
mpDockMouse = new QDockWidget(this);
mpDockMouse->hide();
void mTitleBar::mousePressEvent(QMouseEvent *event)
{
if(event->button() == Qt::LeftButton)
{
mPressBool = true;
//获得鼠标的初始位置
mouseStartPoint = event->globalPos();
//获得窗口的初始位置
mpDockMouse = qobject_cast<QDockWidget*>(parentWidget());
mwindowTopLeftPoint = mpDockMouse->frameGeometry().topLeft();
}
}
void mTitleBar::mouseMoveEvent(QMouseEvent *event)
{
if(mPressBool)
{
//获得鼠标移动的距离
QPoint distance = event->globalPos() - mouseStartPoint;
//改变窗口的位置
mpDockMouse = qobject_cast<QDockWidget*>(parentWidget());
mpDockMouse->move(mwindowTopLeftPoint + distance);
}
}
void mTitleBar::mouseReleaseEvent(QMouseEvent *event)
{
if(event->button() == Qt::LeftButton)
{
mPressBool = false;
}
}