PyQt QDoubleSpinBox

QDoubleSpinBox

The QDoubleSpinBox class provides a double spin box widget that allows you to select and adjust mistakes.

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

class MyApp(QWidget):

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

    def initUI(self):
        self.lbl1 = QLabel('QDoubleSpinBox')
        self.dspinbox = QDoubleSpinBox()
        self.dspinbox.setRange(0, 100)
        self.dspinbox.setSingleStep(0.5)
        self.dspinbox.setPrefix('$ ')
        self.dspinbox.setDecimals(1)
        self.lbl2 = QLabel('$ 0.0')

        self.dspinbox.valueChanged.connect(self.value_changed)

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

        self.setLayout(vbox)

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

def value_changed(self):
        self.lbl2.setText('$ ' + str(self.dspinbox.value()))

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

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

qdoublespinbox pyqt

Related course: Create Desktop Apps with Python PyQt5

Description

self.dspinbox = QDoubleSpinBox()
self.dspinbox.setRange(0, 100)
self.dspinbox.setSingleStep(0.5)

Create one QDoubleSpinBox object (self.dspinbox).

You can use the setRange() method to limit the selection. The default is 0.0 for the minimum and 99.99 for the maximum.

Use the setSingleStep() method to set one step to 0.5.

self.dspinbox.setPrefix('$ ')
self.dspinbox.setDecimals(1)

Using setRefix(), you can set the characters that precede the number. setSuffix() has a letter after the number.

Use setDecimals() to set the number of digits that will be displayed below the decimal point.

self.dspinbox.valueChanged.connect(self.value_changed)

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

vbox = QVBoxLayout()
vbox.addWidget(self.lbl1)
vbox.addWidget(self.dspinbox)
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.dspinbox.value()))

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

Related course: Create Desktop Apps with Python PyQt5