QML控件拖动并靠边停留

来源:互联网 发布:线上展厅制作软件 编辑:程序博客网 时间:2024/05/17 23:04

前言

用QML做控件拖动,当鼠标按下要拖动的按钮然后移动鼠标,控件坐标会随着鼠标而移动,释放鼠标后判断当前的控件位置,然后选择要停留在父窗口的左边还是右边,再通过动画将控件移动到边上。这种场景在做工具栏悬浮按钮的时候比较常见。

正文

实现方式很简单,通过Drag类来实现,并且参考了Qt帮助文档中的示例。
直接上代码吧

import QtQuick 2.6  Item {      id:root      width: 500; height: 400      Rectangle {          id:rect          x: 10; y: 10          width: 50; height: 50          color: "red"          NumberAnimation on x{              id:ani              duration: 400              easing.type: Easing.OutCubic          }          Drag.active: dragArea.drag.active          MouseArea {              id: dragArea              anchors.fill: parent              drag.target: parent              drag.maximumY:root.height-rect.height              drag.minimumY: 0              onPositionChanged: {                  console.log("x",mouseX,"y",mouseY,rect.x,rect.y)              }              onReleased: {                  if(rect.x > root.width/2.){                      ani.to = root.width - rect.width                      ani.start()                  }                  else{                      ani.to = 0                      ani.start()                  }              }          }      }  }

来看看效果图
这里写图片描述

0 0
原创粉丝点击