【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:切换到关于页
相关推荐
geovindu15 分钟前
rust: Chain of Responsibility Pattern
开发语言·后端·设计模式·rust·责任链模式·行为模式
geovindu2 小时前
rust: Chain of Responsibility Pattern (续)
开发语言·后端·设计模式·rust·责任链模式·行为模式
Amos_Web2 小时前
Rspack 源码解析(二十四):AssetPlugin 如何让图片同时是「URL 字符串」和「真实文件」
前端·rust·前端框架
wflynn1 天前
GitHub 今日推荐|solidcraft:Rust 跨平台参数化 CAD,支持 AI 代理通过 MCP 协议驱动建模
rust·开源·github·cad·3d-modeling·brep
geovindu1 天前
rust: pool Pattern
开发语言·后端·设计模式·rust·对象池简写模式
Source.Liu1 天前
【A11】客户端登录流程笔记
windows·rust
william_yangshun1 天前
WordCraft 观察:纯 Rust 重写文字处理器,把文档变成可编程对象
开发语言·后端·rust·文档自动化
geovindu1 天前
rust: pool Pattern (续)
开发语言·后端·设计模式·rust·对象池简写模式
滕州市燕猫虎计算机科技工作室个体工商户2 天前
《Rust程序设计》学习笔记八:结构体
笔记·学习·rust·rust程序设计