Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: How to distinguish between long, short button press and click

Tags:

python

pyqt

I want to have a simple GUI with 4 buttons. If you just click the button, function A should be executed, for short button press (e.g.1sec) function B should be executed and finally a long press (e.g. > 2s) function C should be executed. Imagine a counter. If you click the button, it will be reset to 0 If you short press the button, counter will be increased by 1 for e.g t=1sec If you long press the button, counter will be increased by 10 until button is released.

Is somebody haveing an idea. I was trying this to accomplish it with a 2nd thread but I haven't found a possibility to stop the thread like you can start it

like image 405
Generalf Avatar asked Mar 28 '26 13:03

Generalf


1 Answers

This is easy to do in PyQt if you use a widget which inherits QAbstractButton. No need for any timers or separate threads. Just use the built-in auto-repeat functionality, and keep a record of the current state.

Here's a simple demo:

from PyQt4 import QtGui, QtCore

class Button(QtGui.QPushButton):
    def __init__(self, *args, **kwargs):
        QtGui.QPushButton.__init__(self, *args, **kwargs)
        self.setAutoRepeat(True)
        self.setAutoRepeatDelay(1000)
        self.setAutoRepeatInterval(1000)
        self.clicked.connect(self.handleClicked)
        self._state = 0

    def handleClicked(self):
        if self.isDown():
            if self._state == 0:
                self._state = 1
                self.setAutoRepeatInterval(50)
                print 'press'
            else:
                print 'repeat'
        elif self._state == 1:
            self._state = 0
            self.setAutoRepeatInterval(1000)
            print 'release'
        else:
            print 'click'

if __name__ == '__main__':

    import sys
    app = QtGui.QApplication(sys.argv)
    button = Button('Test Button')
    button.show()
    sys.exit(app.exec_())
like image 87
ekhumoro Avatar answered Mar 30 '26 02:03

ekhumoro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!