Qt-quick(qml)实现窗口和物体的拖动

Qt-quick(qml)实现窗口和物体的拖动

*在实现窗口的拖动时,是在去掉窗口标题栏情况下完成的,当有窗口标题栏后无法展示窗口拖动效果。*

代码实现如下:

import QtQuick 2.9
import QtQuick.Window 2.2

Window {
   id: mainWindow
   visible: true
   width: 900
   height: 600
   title: qsTr("Hello World")
   flags: Qt.Window | Qt.FramelessWindowHint //去标题栏

//    Rectangle {
//        id: rect1
//        x: 12; y: 12
//        width: 76; height: 96
//        color: "lightsteelblue"
//   }

   MouseArea { //为窗口添加鼠标事件
       anchors.fill: parent
       acceptedButtons: Qt.LeftButton //只处理鼠标左键
       property point clickPos: "0,0"
       onPressed: { //接收鼠标按下事件
               clickPos  = Qt.point(mouse.x,mouse.y)
       }
       onPositionChanged: { //鼠标按下后改变位置
               //鼠标偏移量
               var delta = Qt.point(mouse.x-clickPos.x, mouse.y-clickPos.y)

               //如果mainwindow继承自QWidget,用setPos
               mainWindow.setX(mainWindow.x+delta.x)
               mainWindow.setY(mainWindow.y+delta.y)
//               rect1.x = rect1.x + delta.x
//               rect1.y = rect1.y + delta.y
       }
   }
}

实现窗体内物体的拖动
有无标题栏都可以
代码实现如下:

import QtQuick 2.9
import QtQuick.Window 2.2

Window {
   id: mainWindow
   visible: true
   width: 900
   height: 600
   title: qsTr("Hello World")
   //flags: Qt.Window | Qt.FramelessWindowHint //去标题栏

    Rectangle {
        id: rect1
        x: 12; y: 12
        width: 76; height: 96
        color: "lightsteelblue"

        MouseArea { //为窗口添加鼠标事件
            anchors.fill: parent
            acceptedButtons: Qt.LeftButton //只处理鼠标左键
            property point clickPos: "0,0"
            onPressed: { //接收鼠标按下事件
                    clickPos  = Qt.point(mouse.x,mouse.y)
            }
            onPositionChanged: { //鼠标按下后改变位置
                    //鼠标偏移量
                    var delta = Qt.point(mouse.x-clickPos.x, mouse.y-clickPos.y)
                    
                    //如果mainwindow继承自QWidget,用setPos
     //               mainWindow.setX(mainWindow.x+delta.x)
     //               mainWindow.setY(mainWindow.y+delta.y)
                    rect1.x = rect1.x + delta.x
                    rect1.y = rect1.y + delta.y
            }
        }
   }

}

效果如下,可拖动方块:
在这里插入图片描述

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值