【Rust GUI开发入门】编写一个本地音乐播放器(13. 实现按键绑定)

本系列教程对应的代码已开源在 Github zeedle

本篇文章介绍Slint UI如何为播放器页面添加按键绑定,核心思路是当窗口聚焦时,扫描用户按键输入,命中指定按键时,自动调用相关回调函数 。Slint UI支持FocusScope来处理上述逻辑:

slint 复制代码
export component MainWindow inherits Window {
    
    ...
    
    forward-focus: key-input-handler;
	
	...
	
    key-input-handler := FocusScope {
        key-released(event) => {
            if event.text == Key.Space {
                root.toggle_play();
                return accept;
            } else if event.text == Key.RightArrow || event.text == Key.DownArrow {
                root.play_next();
                return accept;
            } else if event.text == Key.LeftArrow || event.text == Key.UpArrow {
                root.play_prev();
                return accept;
            } else if event.text == Key.F1 {
                tabs.current-index = 0;
                return accept;
            } else if event.text == Key.F2 {
                tabs.current-index = 1;
                return accept;
            } else if event.text == Key.F3 {
                tabs.current-index = 2;
                return accept;
            } else if event.text == Key.F4 {
                tabs.current-index = 3;
                return accept;
            }
            return reject;
        }
    }
}

代码解释

上述代码指定了,当某个按键按下时,所触发的操作:

  • 空格键:播放/暂停当前歌曲
  • 上键头/左键头:上一首歌曲
  • 下箭头。右箭头:下一首歌曲
  • F1:切换到音乐列表页
  • F2:切换到歌词页
  • F3:切换到设置页
  • F4:切换到关于页
相关推荐
EniacCheng2 天前
【RUST】学习笔记-整型
笔记·学习·rust
小灰灰搞电子3 天前
Rust可以取代C++么?
开发语言·c++·rust
百锦再3 天前
京东云鼎入驻方案解读——通往协同的“高架桥”与“快速路”
android·java·python·rust·django·restful·京东云
异步思考者3 天前
Rust实战:一个内存消息队列的 Trait 驱动开发
rust
受之以蒙3 天前
智能目标检测:用 Rust + dora-rs + yolo 构建“机器之眼”
人工智能·笔记·rust
熬了夜的程序员3 天前
【Rust学习之路】第 0 章:理解 Rust 的核心哲学
开发语言·学习·rust
EniacCheng3 天前
【RUST】学习笔记-环境搭建
笔记·学习·rust
禅思院3 天前
在win10上配置 Rust以及修改默认位置问题
开发语言·前端·后端·rust·cargo·mingw64·cargo安装位置
shandianchengzi3 天前
【记录】Rust|Rust开发相关的7个VSCode插件的介绍和推荐指数(2025年)
开发语言·vscode·rust
JPX-NO3 天前
Rust + Rocket + Diesel构建的RESTful API示例(CRUD)
开发语言·rust·restful