引言
本文旨在一个问题的记录:自定义窗口拖动的过程中,窗口不能很好的跟随鼠标移动,此外会出现窗口拖动时抖动。
下面是上文描述的效果:
拖动时窗口抖动
本文针对上面的问题,找出解决方法,且说明为什么。
开发环境
使用QtCreator开发。其相关的Qt库使用Qt6.6.0。
关键性代码
这里只给出自定义窗口拖动功能需要的部分关键代码。
//窗口拖动相关变量声明
QPointF m_pressPos;//鼠标按下时位置
QPointF m_topLeftPos;//自定义窗口左上角的位置
bool m_isPress;//鼠标左键是否按下
//功能函数定义
void QCustomWidget::mousePressEvent(QMouseEvent *event)
{
qDebug()<<"mousePressEvent";
if(event->button() == Qt::LeftButton){
m_pressPos = event->position();//相对于接收事件的窗口或者项,事件发生时的位置坐标
m_topLeftPos = geometry().topLeft();
m_isPress = true;
}
qDebug()<<"m_pressPos="<<m_pressPos<<", m_topLeftPos="<<m_topLeftPos;
QWidget::mousePressEvent(event);
}
void QCustomWidget::mouseReleaseEvent(QMouseEvent *event)
{
m_isPress = false;
QWidget::mouseReleaseEvent(event);
}
void QCustomWidget::mouseMoveEvent(QMouseEvent *event)
{
qDebug()<<"mouseMoveEvent";
if(m_isPress && event->type()