如何为QML TextArea的cursorDelegate实现类Microsoft Word的光标动画?
实现类似Microsoft Word的QML文本框光标闪烁效果
要实现Word那种周期性闪烁的光标,核心是给光标添加透明度循环动画,同时结合文本框的焦点状态控制动画启停,让效果更贴合实际使用场景。修改后的代码如下:
TextArea { anchors.fill: parent id: textArea width: 200 height: 100 text: "Hello World!" font.pixelSize: 20 selectByMouse: true cursorPosition: 0 cursorDelegate: Rectangle{ id: cursor width: 2 color: "black" // 匹配文本行高,让光标垂直对齐更自然 height: textArea.font.pixelSize + 4 // 光标闪烁动画:透明度在0和1之间循环切换 PropertyAnimation on opacity { from: 1 to: 0 duration: 500 loops: Animation.Infinite // 仅文本框获得焦点时播放动画 running: textArea.activeFocus } } }
关键细节说明:
- 调整光标宽度为
2,更贴近Word默认光标样式,同时设置height匹配文本行高,避免光标与文本错位 - 使用
PropertyAnimation控制光标透明度,duration:500对应0.5秒一次闪烁周期,loops: Animation.Infinite让动画持续循环 - 通过
running: textArea.activeFocus绑定焦点状态,只有文本框处于激活状态时光标才闪烁,失去焦点后光标保持显示(若需要失焦隐藏,可修改opacity默认值为0)
如果想要更流畅的过渡效果,也可以替换为OpacityAnimator,用法一致:
OpacityAnimator { target: cursor from: 1 to: 0 duration: 500 loops: Animation.Infinite running: textArea.activeFocus }
内容的提问来源于stack exchange,提问作者cryfeifei
相关产品推荐
相关产品推荐

