Rust Slint 实现控件拖动详细教程
Rust Slint 实现控件拖动详细教程
- 一、源码分享
- 1、效果展示
- 2、源码分享
- 二、实现原理
- 1、基本用法
- 2、主要属性
- 3、事件处理
- 4、高级用法
- 5、注意事项
一、源码分享
1、效果展示
2、源码分享
import { AboutSlint, VerticalBox, LineEdit, HorizontalBox, Button, GroupBox, GridBox, ComboBox, Spinner, Slider, ListView, Palette, ProgressIndicator, CheckBox, Switch } from "std-widgets.slint";export component MainWindow inherits Window {min-width: 700px;min-height: 50px;preferred-width: 1300px;preferred-height: 850px;title: "Slint Demo";background: #f0f0f0;private property <Point> pressed_point;private property <bool> is_pressed: false;Rectangle {width: 100px;height: 100px;background: red;TouchArea {pointer-event(event) => {if event.kind == PointerEventKind.down && event.button == PointerEventButton.left {root.is_pressed = true;root.pressed_point.x = self.mouse-x;root.pressed_point.y = self.mouse-y} else if event.kind == PointerEventKind.up && event.button == PointerEventButton.left {root.is_pressed = false;}}moved => {if(root.is_pressed){parent.x += self.mouse-x - root.pressed_point.x;parent.y += self.mouse-y - root.pressed_point.y;}}}}
}
二、实现原理
主要通过TouchArea
监听鼠标位置,从而改变x、y属性实现。
TouchArea是Slint UI框架中用于处理触摸和鼠标事件的透明区域组件。它本身不可见,但可以捕获用户的交互行为并触发回调函数。
1、基本用法
在.slint文件中声明TouchArea:
import { TouchArea } from "std-widgets.slint";export component MyComponent {TouchArea {width: 100px;height: 50px;clicked => { /* 处理点击事件 */ }}
}
2、主要属性
width
和height
:定义触摸区域尺寸enabled
:布尔值,控制是否响应用户交互has-hover
:布尔值,指示是否检测悬停状态pressed
:布尔属性,反映当前按压状态
3、事件处理
TouchArea支持多种交互事件:
TouchArea {clicked => { /* 单击事件 */ }double-clicked => { /* 双击事件 */ }moved => { /* 移动事件 */ }
}
4、高级用法
结合其他组件实现交互效果:
export component ToggleButton {in-out property <bool> checked;width: 40px;height: 20px;TouchArea {width: parent.width;height: parent.height;clicked => {root.checked = !root.checked;}}
}
5、注意事项
- TouchArea会拦截所有触摸/鼠标事件,阻止事件向父组件传递
- 多个重叠的TouchArea组件中,只有最上层的会接收事件
- 在移动端开发时,建议设置合理的触摸区域大小(至少48x48像素)