Search code examples
pythonpyqtpyqt5qspinbox

QSpinbox with binary numbers


Is it possible to have spinbox with binary inputs. Lets say "10010". and scroll up and down does binary increment/decrement.


Solution

  • You have to set the displayIntegerBase property to 2 to use the binary system:

    import sys
    
    from PyQt5 import QtWidgets
    
    
    if __name__ == "__main__":
        app = QtWidgets.QApplication(sys.argv)
        w = QtWidgets.QSpinBox()
        w.setValue(0b10010)
        w.setDisplayIntegerBase(2)
        w.show()
        sys.exit(app.exec_())
    

    Update:

    If you want to set a minimum width (in this case 5) then the textFromValue() method must be overridden:

    import sys
    
    from PyQt5 import QtWidgets
    
    
    class SpinBox(QtWidgets.QSpinBox):
        def textFromValue(self, value):
            return "{:05b}".format(value)
    
    
    if __name__ == "__main__":
        app = QtWidgets.QApplication(sys.argv)
        w = SpinBox()
        w.setMaximum(0b11111)
        w.setValue(0b00000)
        w.setDisplayIntegerBase(2)
        w.show()
        sys.exit(app.exec_())
    

    enter image description here