Qt QWidget和QML实现窗口拖动源码分享

发布于:2025-04-20 ⋅ 阅读:(12) ⋅ 点赞:(0)

一、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
        }
    }
}



网站公告

今日签到

点亮在社区的每一天
去签到