Skip to content
Advertisement

How to reverse spinbox selection in PyQt5?

I have a spinbox in PyQt5 like below. How can I make the selection reversed? i.e. If I click down arrow, the value goes up, vice versa.

spinbox

Advertisement

Answer

A possible solution is to override the stepBy() and stepEnabled() methods:

import sys
from PyQt5 import QtWidgets


class ReverseSpinBox(QtWidgets.QSpinBox):
    def stepEnabled(self):
        if self.wrapping() or self.isReadOnly():
            return super().stepEnabled()
        ret = QtWidgets.QAbstractSpinBox.StepNone
        if self.value() > self.minimum():
            ret |= QtWidgets.QAbstractSpinBox.StepUpEnabled
        if self.value() < self.maximum():
            ret |= QtWidgets.QAbstractSpinBox.StepDownEnabled
        return ret

    def stepBy(self, steps):
        return super().stepBy(-steps)


if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    w = ReverseSpinBox()
    w.resize(320, 20)
    w.show()
    sys.exit(app.exec_())
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement