Welcome to 16892 Developer Community-Open, Learning,Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I hava a QML button, and I want to prevent the button to be clicked before my function call is finished.

I tried the code below and it's not working. Button does not toggle enabled/disabled within the clicked signal. I guess the binding does not take effect immediately.

import QtQuick
import QtQuick.Control

Button {
    onClicked: {
        console.log('clicked')
        this.enabled = false
        do_something()
        this.enabled = true
    }
}

I also tried pressed signal

Button {
    onPressed: {
        console.log('pressed')
        this.enabled = false
    }
    onClicked: {
        console.log('clicked')
        do_something()
        this.enabled = true
    }
}

But the onClicked signal is not triggered at all.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
4.0k views
Welcome To Ask or Share your Answers For Others

1 Answer

If the enabled property binding doesn't work, you can always prevent your function from getting called yourself:

Button {
    onClicked: {
        if (this.enabled) {  // Don't allow multiple clicks
            console.log('clicked')
            this.enabled = false
            do_something()
            this.enabled = true
        }
    }
}

UPDATE:

In response to your own answer to your question, I'd suggest an alternative to a timer is Qt.callLater(). It will essentially post an event on the event queue rather than call the function directly. That allows just enough time for other processing to occur.

Button {
    id: btn
    onClicked: {
        console.log('clicked')
        this.enabled = false
        Qt.callLater(callback);
    }
    function callback() {
        do_something()
        btn.enabled = true
    }
}

But I'm still wondering if you ever tried my original answer, because I think it's much easier, and it should work.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to 16892 Developer Community-Open, Learning and Share
...