PyQt QSpinBox

The QSpinBox class provides a spin box widget that allows you to select and adjust integers. The demo below shows the spin box in a PyQt widget (QWidget).

import sys
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QSpinBox, QVBoxLayout

class MyApp(QWidget):

def __init__(self):
        super().__init__()
        self.initUI()

def initUI(self):
        self.lbl1 = QLabel('QSpinBox')
        self.spinbox = QSpinBox()
        self.spinbox.setMinimum(-10)
        self.spinbox.setMaximum(30)
        # self.spinbox.setRange(-10, 30)
        self.spinbox.setSingleStep(2)
        self.lbl2 = QLabel('0')

self.spinbox.valueChanged.connect(self.value_changed)

vbox = QVBoxLayout()
        vbox.addWidget(self.lbl1)
        vbox.addWidget(self.spinbox)
        vbox.addWidget(self.lbl2)
        vbox.addStretch()

self.setLayout(vbox)

self.setWindowTitle('QSpinBox')
        self.setGeometry(300, 300, 300, 200)
        self.show()

def value_changed(self):
        self.lbl2.setText(str(self.spinbox.value()))

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = MyApp()
    sys.exit(app.exec_())

Two labels (self.lbl1, self.lbl2) and a spinbox widget (self.spinbox) appear in the window.

spinbox pyqt

Related course: Create Desktop Apps with Python PyQt5

Description

self.spinbox = QSpinBox()
self.spinbox.setMinimum(-10)
self.spinbox.setMaximum(30)

Create one QSpinBox object (self.spinbox).

You can use the setMinimum() and setMaximum() methods to limit the selection. The minimum value is 0 and the maximum value is 99 is the default.

self.spinbox.setRange(-10, 30)

The setRange() method is the same as setMinimum() and setMaximum().

self.spinbox.setSingleStep(2)

Set one step to 2 using setSingleStep().

For spin boxes, the minimum value that can be set in one step is 1.

self.spinbox.valueChanged.connect(self.value_changed)

Connect the valueChanged, which occurs when the value of the spin box widget changes, self.value_changed to the method.

vbox = QVBoxLayout()
vbox.addWidget(self.lbl1)
vbox.addWidget(self.spinbox)
vbox.addWidget(self.lbl2)
vbox.addStretch()

self.setLayout(vbox)

Use the vertical box layout to place two labels and a spin box widget vertically, and set them to the layout of the entire widget.

def value_changed(self):
    self.lbl2.setText(str(self.spinbox.value()))

When the value of the spin box changes, set the text in self.lbl2 to the value of the spin box (self.spinbox.value()).