fsoto
fsoto

Reputation: 78

Qspinbox value changed signal only for arrows changes

I need to identify when an user changes a value from an spinbox, but only if the change was made using the arrows (up or down according to step).

I used the valueChanged signal, but this signal is emmited also when the user change the value by hand (editing the numbers), I want to avoid this behavior.

I'm using PyQt5

Upvotes: 2

Views: 1164

Answers (1)

eyllanesc
eyllanesc

Reputation: 244311

In this case you can trace the change by overwriting the mousePressEvent method:

from PyQt5 import QtCore, QtWidgets

class SpinBox(QtWidgets.QSpinBox):
    upClicked = QtCore.pyqtSignal()
    downClicked = QtCore.pyqtSignal()

    def mousePressEvent(self, event):
        last_value = self.value()
        super(SpinBox, self).mousePressEvent(event)
        if self.value() < last_value:
            self.downClicked.emit()
        elif self.value() > last_value:
            self.upClicked.emit()

if __name__ == '__main__':
    import sys
    app = QtWidgets.QApplication(sys.argv)
    s = SpinBox()
    l = QtWidgets.QLabel(alignment=QtCore.Qt.AlignCenter)
    w = QtWidgets.QWidget()

    s.upClicked.connect(lambda: l.setText("Up"))
    s.downClicked.connect(lambda: l.setText("Down"))

    lay = QtWidgets.QVBoxLayout(w)
    lay.addWidget(s)
    lay.addWidget(l)
    w.resize(320, w.sizeHint().height())
    w.show()
    sys.exit(app.exec_())

Upvotes: 2

Related Questions