我有一个 QML 按钮,我想防止在函数调用完成之前单击该按钮。
我尝试了下面的代码,但它不起作用。按钮不会在clicked信号内切换启用/禁用。我猜绑定不会立即生效。
import QtQuick
import QtQuick.Control
Button {
onClicked: {
console.log('clicked')
this.enabled = false
do_something()
this.enabled = true
}
}
Run Code Online (Sandbox Code Playgroud)
我也试过pressed信号
Button {
onPressed: {
console.log('pressed')
this.enabled = false
}
onClicked: {
console.log('clicked')
do_something()
this.enabled = true
}
}
Run Code Online (Sandbox Code Playgroud)
但onClicked信号根本没有触发。
如果enabled属性绑定不起作用,您始终可以防止自己调用您的函数:
Button {
onClicked: {
if (this.enabled) { // Don't allow multiple clicks
console.log('clicked')
this.enabled = false
do_something()
this.enabled = true
}
}
}
Run Code Online (Sandbox Code Playgroud)
更新:
为了回应您自己对问题的回答,我建议计时器的替代方法是Qt.callLater(). 它本质上会在事件队列上发布一个事件,而不是直接调用该函数。这为其他处理的发生提供了足够的时间。
Button {
id: btn
onClicked: {
console.log('clicked')
this.enabled = false
Qt.callLater(callback);
}
function callback() {
do_something()
btn.enabled = true
}
}
Run Code Online (Sandbox Code Playgroud)
但是我仍然想知道您是否尝试过我原来的答案,因为我认为它更容易,而且应该有效。
最后我自己找到了答案。用户像 html/javascript 一样使用 setTimeout 来延迟执行。由于QML没有setTimeout,所以需要添加一个Timer。
import QtQuick
import QtQuick.Control
Timer { id: timer }
Button {
id: btn
onClicked: {
console.log('clicked')
this.enabled = false
timer.interval = 100 // a short delay, enabled status would change properly.
timer.triggered.connect(callback)
timer.start()
}
function callback() {
do_something()
timer.triggered.disconnect(callback) // don't forget to remove the callback
btn.enabled = true
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
270 次 |
| 最近记录: |