为盲打训练器选择合适的QML文本显示类
QML盲打训练器文本组件实现方案
不用纠结TextEdit/TextArea的原生光标逻辑,直接用自定义组合组件更灵活,核心思路是:
- 用
Text组件显示待输入文本,通过字符串截取实现“左移”效果 - 叠加一个固定位置的光标(比如用
Rectangle模拟) - 监听键盘输入,匹配正确字符后更新文本内容
核心代码示例
import QtQuick 2.15 import QtQuick.Controls 2.15 Item { width: 400 height: 60 // 待输入的原始文本 property string sourceText: "The quick brown fox jumps over the lazy dog" // 当前已输入正确的字符索引 property int currentIndex: 0 // 显示当前需要输入的文本段(从currentIndex开始) Text { id: displayText anchors.centerIn: parent text: sourceText.substring(currentIndex) font.pixelSize: 32 color: "#333" // 高亮下一个要输入的字符 Text { text: displayText.text.charAt(0) font.pixelSize: 32 color: "#ff4444" anchors.left: parent.left anchors.top: parent.top } } // 固定位置的光标 Rectangle { id: cursor width: 2 height: displayText.font.pixelSize + 4 color: "#000" anchors.left: displayText.left anchors.top: displayText.top anchors.topMargin: -2 // 光标闪烁动画 PropertyAnimation on opacity { from: 1 to: 0 duration: 500 loops: Animation.Infinite } } // 监听键盘输入 Keys.onPressed: { let targetChar = sourceText.charAt(currentIndex) if (event.text === targetChar) { currentIndex++ // 防止索引越界 if (currentIndex >= sourceText.length) { currentIndex = 0 } } } focus: true }
关键逻辑说明
- 文本左移效果:通过
sourceText.substring(currentIndex)截取剩余文本,每输入正确一个字符,currentIndex加1,自然实现文本左移 - 固定光标:用独立的
Rectangle模拟光标,锚定在显示文本的起始位置,不受文本内容变化影响 - 输入校验:直接监听键盘输入,匹配当前目标字符后更新索引,逻辑简单直接
这种方案比修改TextEdit/TextArea的原生行为更可控,完全符合你要的“光标固定、正确输入后文本左移”的需求。
内容的提问来源于stack exchange,提问作者EL96cpp
相关产品推荐
相关产品推荐

