QSpinBox

The QSpinBox class provides a spinbox widget that lets you select and control integers.

For further details, check QSpinBox official document .


Example

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) appears on the window.


Description

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

Make a QSpinBox object(self.spinbox).

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


# self.spinbox.setRange(-10, 30)

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


self.spinbox.setSingleStep(2)

Use setSingleStep() to set one step as 2.

For spin box, the minimum value that can be set as a single step is 1.


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

Connect the signal that occurs when the value of the spinbox widget is changed (valueChanged) to the self.value_changed 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 spin-box widget vertically, and set it as 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 of self.lbl2 as the value of spinbox (self.spinbox.value()).


Results

../_images/4_14_qspinbox.png ../_images/4_14_qspinbox_mac.png

Figure 5-14. Use QSpinBox to make spinbox widget.


Prev/Next