QDoubleSpinBox

QDoubleSpinBox class provides a double spin box widget that lets you select and control mistakes.

For further details, check QDoubleSpinBox official document .


Example

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 spin box widget(self.spinbox) appear on the window.


Description

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

Make a QDoubleSpinBox object(self.dspinbox).

setRange() method helps you limit the range of selection. By default, the minimum value is 0.0 and the maximum is 99.99.

Use setSingleStep() method to make a single step 0.5.


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

setPrefix() to sets the character that will come in front of the number. setSuffix() makes the character come behind the number.

setDecimals() sets the number of decimal places to be displayed.


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

Associate the signal that occurs when the value of the double spin box widget is changed (valueChanged) with the self.value_changed 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 double-spin box widget vertically, and set it as 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, make the text of self.lbl2 be the value for the double spin box (self.dspinbox.value()).


Results

../_images/4_15_qdoublespinbox.png ../_images/4_15_qdoublespinbox_mac.png

Figure 5-15. Using QDoubleSpinBox for double spin box widget.


Prev/Next

Prev :
Next :