【问题标题】:How to break a signal chain in QML?如何打破 QML 中的信号链?
【发布时间】:2020-09-28 12:50:20
【问题描述】:

通过在 QML 中编辑手动文本字段,调用一系列信号:textEdited(),然后是 textChanged()。我有两个处理程序,一个用于 onTextEdited,另一个用于 onTextChanged

如何在 TextEdited() 处理程序中阻止 textChanged() 调用? 如何中断信号调用序列?

TextField {
    id: _field
    background: _textBackground

    onTextChanged: {
        _textBackground.border.color = "#FFBDBDBD"
        _textBackground.border.width = 1
    }

    onTextEdited: {
        _textBackground.border.color = "#FFE57439"
        _textBackground.border.width = 2
    }
}

Rectangle {
    id: _textBackground
    border {
        width: 1
        color: "#FFBDBDBD"
    }
}

【问题讨论】:

  • 你想用这段代码做什么?我不明白实际目标是什么。
  • @GrecKo TextField 字段中的代码可以通过编程和手动方式更改。当以编程方式更改时,触发TextChanged() 信号,手动时首先触发TextEdited() 信号,然后自动触发TextChanged() 信号。所以我不希望TextChanged() 信号在TextEdited() 信号之后触发。程序代码已被简化,以便更好地理解问题。

标签: qt qml


【解决方案1】:

您不应试图阻止信号的发出。相反,您应该尝试找到一种优雅的方式来实现您想要的目标。


据我了解,您有两个要求:

  1. 手动编辑文本时执行一些代码

    只要手动更改文本,就会发出信号onTextEdited。因此,它非常适合您的要求

  2. 以编程方式编辑文本时执行一些代码

    onTextChanged 信号总是在文本更改时发出。因此,它不适用于此要求。

    你可以例如使用函数以编程方式更改文本并执行附加代码。


最后你的代码可能看起来像这样:

TextField {
    id: _field
    background: _textBackground

    onTextEdited: {
        _textBackground.border.color = "#FFE57439"
        _textBackground.border.width = 2
    }

    // Call this function whenever the 'text' property should be changed programmatically
    function changeTextProgrammatically(newText) {
        text = newText
        
        _textBackground.border.color = "#FFBDBDBD"
        _textBackground.border.width = 1
    }
}

【讨论】:

  • 非常感谢!
【解决方案2】:

我通过在代码中引入 isEdit 标志找到了解决方案。

TextField {
    id: _field
    property bool isEdit: false
    background: _textBackground

    onTextChanged: {
        if (!isEdit)
        {
            _textBackground.border.color = "#FFBDBDBD";
            _textBackground.border.width = 1;
        }
        isEdit = false;
    }

    onTextEdited: {
        isEdit = true;
        _textBackground.border.color = "#FFE57439";
        _textBackground.border.width = 2;
    }
}

Rectangle {
    id: _textBackground
    border {
        width: 1
        color: "#FFBDBDBD"
    }
}

onTextEdited 信号处理程序执行后,onTextChanged 处理程序被执行,但它包含检查 onTextEdited 处理程序是否先前被执行过.如果处理程序已执行,则跳过条件语句的主体。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-11-13
    • 2022-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多