You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为盲打训练器选择合适的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
}

关键逻辑说明

  1. 文本左移效果:通过sourceText.substring(currentIndex)截取剩余文本,每输入正确一个字符,currentIndex加1,自然实现文本左移
  2. 固定光标:用独立的Rectangle模拟光标,锚定在显示文本的起始位置,不受文本内容变化影响
  3. 输入校验:直接监听键盘输入,匹配当前目标字符后更新索引,逻辑简单直接

这种方案比修改TextEdit/TextArea的原生行为更可控,完全符合你要的“光标固定、正确输入后文本左移”的需求。

内容的提问来源于stack exchange,提问作者EL96cpp

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 00:15:04