Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.5k views
in Technique[技术] by (71.8m points)

qt - How to prevent QML button multiple click in a short period?

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...