PyQt5 QDoubleSpinBox - Setting Value

PyQt5 QDoubleSpinBox - Setting Value

In PyQt5, a QDoubleSpinBox widget allows the user to select a floating-point number. You can set its value programmatically using the setValue method. Here's a basic example to demonstrate how to use QDoubleSpinBox and set its value:

Step 1: Import PyQt5 Modules

First, import the necessary PyQt5 modules:

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

Step 2: Create the Main Window Class

Create a class for your main window and set up the QDoubleSpinBox in it:

class MainWindow(QWidget): def __init__(self): super().__init__() # Create a QVBoxLayout layout = QVBoxLayout(self) # Create a QDoubleSpinBox self.doubleSpinBox = QDoubleSpinBox(self) # Set the value of the spin box self.doubleSpinBox.setValue(10.5) # Setting to a value of 10.5 # Optionally set range if needed self.doubleSpinBox.setRange(0, 100) # Add the spin box to the layout layout.addWidget(self.doubleSpinBox) # Set the layout for the main window self.setLayout(layout) 

In this example, a QDoubleSpinBox is created and its value is set to 10.5. You can also set the range of the spin box using setRange.

Step 3: Run the Application

Create an instance of QApplication and your MainWindow class, and then start the event loop:

if __name__ == "__main__": app = QApplication(sys.argv) mainWin = MainWindow() mainWin.show() sys.exit(app.exec_()) 

Complete Example

Here's the complete code that combines the steps mentioned above:

from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QDoubleSpinBox import sys class MainWindow(QWidget): def __init__(self): super().__init__() layout = QVBoxLayout(self) self.doubleSpinBox = QDoubleSpinBox(self) self.doubleSpinBox.setValue(10.5) # Set initial value self.doubleSpinBox.setRange(0, 100) # Set the range layout.addWidget(self.doubleSpinBox) self.setLayout(layout) if __name__ == "__main__": app = QApplication(sys.argv) mainWin = MainWindow() mainWin.show() sys.exit(app.exec_()) 

When you run this application, it will display a window with a QDoubleSpinBox initialized to a value of 10.5. Users can adjust the value within the specified range using the spin box's arrows.


More Tags

leading-zero sharepoint-2010 mach .net-4.0 ng-build moment-timezone stripe-payments r.java-file cross-join pm2

More Programming Guides

Other Guides

More Programming Examples