如何解决如何在QML中打破信号链?
通过在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"
}
}
解决方法
您不应尝试阻止信号的发射。相反,您应该尝试找到一种优雅的方式来实现您想要的目标。
据我了解,您有两个要求:
-
手动编辑文本时执行一些代码
每手动更改文本就会发出信号
onTextEdited
。因此,它非常适合您的需求 -
以编程方式编辑文本时执行一些代码
当文本更改时,信号
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
}
}
,
我通过在代码中引入 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 处理程序是否先前已执行的功能。 。如果处理程序已执行,则将跳过条件语句的正文。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。