一、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.Dialogs
ApplicationWindow {
id:root
width: 100
height: 150
property point movePressStartPoint: Qt.point(0,0)
property bool movePressed: false
MouseArea{
anchors.fill: parent
cursorShape: Qt.OpenHandCursor
acceptedButtons: Qt.LeftButton
hoverEnabled: true
onPressed:(mouse)=> {
if(mouse.button === Qt.LeftButton){
movePressStartPoint.x = mouseX
movePressStartPoint.y = mouseY
movePressed = true
}
}
onReleased: (mouse)=> {
if(mouse.button === Qt.LeftButton){
movePressed = false;
}
}
onMouseXChanged: {
if(!movePressed)
return
var x = root.x + mouseX - movePressStartPoint.x
root.x = x
}
onMouseYChanged: {
if(!movePressed)
return
var y = root.y + mouseY - movePressStartPoint.y
root.y = y
}
}
}