PySide2基础篇(十一)——QSpinBox运用
前言:
阅读这篇文章我能学到什么?
数字输入框即限制只能输入数字内容,也可以限制输入的数字范围。是输入数字信息时首选的控件
——如果你觉得这是一篇不错的博文,希望你能给一个小小的赞,感谢您的支持。
1 创建数字输入框
通过类QSpinBox
可以实例化数字输入框控件。
代码示例:
from PySide2.QtWidgets import QApplication, QMainWindow, QSpinBox
from PySide2.QtCore import Slot
app = QApplication([])
MainWindow = QMainWindow()
SpinBox = QSpinBox(MainWindow)
SpinBox.resize(100, 20)
SpinBox.value()
SpinBox.setRange(0, 100) #设置数值范围
MainWindow.show()
app.exec_()
运行结果:
我们限制了数值范围在0~100,因此可以看到无法将值设置为超出范围的值。
2 输入框的其他功能
输入框同样可以设置值、读取值、失能置灰。
代码示例:
from PySide2.QtWidgets import QApplication, QMainWindow, QSpinBox, QPushButton
from PySide2.QtCore import Slot
app = QApplication([])
MainWindow = QMainWindow()
GetValueButton = QPushButton(MainWindow)
GetValueButton.setText("读取")
GetValueButton.resize(50, 20)
GetValueButton.move(120, 0)
SetValueButton = QPushButton(MainWindow)
SetValueButton.setText("50")
SetValueButton.resize(50, 20)
SetValueButton.move(120, 20)
EnableButton = QPushButton(MainWindow)
EnableButton.setText("Enable")
EnableButton.resize(50, 20)
EnableButton.move(120, 40)
SpinBox = QSpinBox(MainWindow)
SpinBox.resize(100, 20)
SpinBox.value()
SpinBox.setRange(0, 100) #设置数值范围
@Slot()
def GetValue():
print(SpinBox.value())
@Slot()
def SetValue():
SpinBox.setValue(50)
bEnable = False
@Slot()
def CtrlEnable():
global bEnable #声明全局变量
SpinBox.setEnabled(bEnable)
if bEnable == False:
bEnable = True
else:
bEnable = False
GetValueButton.clicked.connect(GetValue)
SetValueButton.clicked.connect(SetValue)
EnableButton.clicked.connect(CtrlEnable)
MainWindow.show()
app.exec_()
运行结果: