一、QWidget实现窗口拖动
.hpp
QPoint pressedPoint;
bool leftBtnPressed = false;
.cpp
bool PetWidget::eventFilter(QObject *obj, QEvent *event)
{if(obj == this){if(event->type() == QEvent::MouseButtonPress){QMouseEvent* e = static_cast<QMouseEvent *>(event);if(e->button() == Qt::LeftButton){this->pressedPoint = e->globalPos() - pos();this->leftBtnPressed = true;}}else if(event->type() == QEvent::MouseMove){QMouseEvent* e = static_cast<QMouseEvent *>(event);if(this->leftBtnPressed){this->move(e->globalPos() - this->pressedPoint);}}else if(event->type() == QEvent::MouseButtonRelease){QMouseEvent* e = static_cast<QMouseEvent *>(event);if(e->button() == Qt::LeftButton){this->leftBtnPressed = false;}}}return false;
}
二、QML实现窗口拖动
import QtQuick
import QtQuick.Controls
import QtQuick.DialogsApplicationWindow {id:rootwidth: 100height: 150property point movePressStartPoint: Qt.point(0,0)property bool movePressed: falseMouseArea{anchors.fill: parentcursorShape: Qt.OpenHandCursoracceptedButtons: Qt.LeftButtonhoverEnabled: trueonPressed:(mouse)=> {if(mouse.button === Qt.LeftButton){movePressStartPoint.x = mouseXmovePressStartPoint.y = mouseYmovePressed = true}}onReleased: (mouse)=> {if(mouse.button === Qt.LeftButton){movePressed = false;}}onMouseXChanged: {if(!movePressed)returnvar x = root.x + mouseX - movePressStartPoint.xroot.x = x}onMouseYChanged: {if(!movePressed)returnvar y = root.y + mouseY - movePressStartPoint.yroot.y = y}}
}