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

QML TextArea修改文本触发递归崩溃问题求助

QML TextArea修改文本触发崩溃:pure virtual method called错误

在使用QML TextArea结合正则表达式做语法高亮时,程序突然崩溃,抛出以下错误:

pure virtual method called
terminate called without an active exception

已做的排查

  • 直接在onTextChanged里给text赋固定值会触发无限递归,后续代码无法执行:
onTextChanged: {
    text = "35" // 此处触发无限递归
    console.log("test") 
}
  • 添加processing标志避免递归后,固定值赋值可正常运行:
onTextChanged: {
    if(!processing) {
        processing = true
        text = "35"
    }
    processing = false
    console.log("test")
}
  • 但只要基于原文本修改(比如text = text + " word"甚至直接text = text),仍会触发崩溃错误。

问题原因

这种崩溃本质是因为在onTextChanged回调里直接修改text时,TextArea内部的文本处理状态还未稳定。尤其是读取原文本再修改的操作,会触发TextArea内部的纯虚函数调用——大概率是内部文本处理相关的虚函数还未完成初始化,或是状态更新时出现了冲突。就算加了processing标志,读取原文本的操作还是会干扰内部状态,导致崩溃。

解决办法

  1. 用Qt.callLater延迟修改
    让TextArea先走完当前的文本更新流程,再执行修改操作:
property bool processing: false

onTextChanged: {
    if(!processing) {
        processing = true
        Qt.callLater(function() {
            text = text + " word"
            processing = false
        })
    }
}
  1. 用中间属性间接更新文本
    避免直接修改text,通过绑定一个中间属性来传递修改后的值:
property string displayText: ""

TextArea {
    text: displayText
    onTextChanged: {
        if(!processing) {
            processing = true
            displayText = text + " word"
            processing = false
        }
    }
    property bool processing: false
}
  1. 换语法高亮的实现方式
    别通过修改文本实现高亮,用TextArea自带的highlighter属性配合SyntaxHighlighter子类来做,从根源避免频繁修改文本导致的状态冲突:
TextArea {
    id: editor
    highlighter: MyHighlighter {}
}

// 自定义高亮器
MyHighlighter {
    id: highlighter
    // 在这里实现正则匹配的语法高亮逻辑,比如给特定关键词添加颜色
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 03:22:48