本文主要是介绍PyQt基础_008_ 按钮类控件QSpinbox,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
基本操作
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *class spindemo(QWidget):def __init__(self, parent=None):super(spindemo, self).__init__(parent)self.setWindowTitle("SpinBox 例子")self.resize(300, 100)layout = QVBoxLayout()self.l1=QLabel("current value:")self.l1.setAlignment(Qt.AlignCenter)layout.addWidget(self.l1)self.sp = QSpinBox()layout.addWidget(self.sp)self.sp.valueChanged.connect(self.valuechange)self.setLayout(layout)def valuechange(self): self.l1.setText("current value:" + str(self.sp.value()) )if __name__ == '__main__':app = QApplication(sys.argv)ex = spindemo()ex.show()sys.exit(app.exec_())
长按加速
import sysfrom PyQt5.Qt import *class MyASB(QAbstractSpinBox):def __init__(self, parent, num: int = 0):super().__init__(parent)self.current_num = 0self.lineEdit().setText(f"{num}")def stepEnabled(self) -> "QAbstractSpinBox.StepEnabled":return QAbstractSpinBox.StepUpEnabled | QAbstractSpinBox.StepDownEnableddef stepBy(self, steps: int) -> None:self.current_num = self.current_num + stepsself.lineEdit().setText(str(self.current_num))class Window(QWidget):def __init__(self):super().__init__()self.setWindowTitle("QAbstractSpinBox-长按累加加速")self.resize(500, 500)self.move(400, 250)self.setup_ui()def setup_ui(self):asb = MyASB(self)asb.resize(120, 30)asb.move(150, 100)# -------累加加速--------asb.setAccelerated(True) # 加速print(asb.isAccelerated())# ------只读---------asb.setReadOnly(True) # 不能通过键盘直接修改数字,但可以通过小箭头控制数字增减print(asb.isReadOnly())if __name__ == "__main__":app = QApplication(sys.argv)window = Window()window.show()sys.exit(app.exec_())
自定义形状
import sysfrom PyQt5.Qt import *# ------自定义展示格式--------
class MySpinBox(QSpinBox):def textFromValue(self, v: int) -> str:# 修改的只是展示效果,真实数值没有变print(v)return str(v) + "*" + str(v)class Window(QWidget):def __init__(self):super().__init__()self.setWindowTitle("QSpinBox")self.resize(500, 500)self.move(400, 250)self.setup_ui()def setup_ui(self):sb = MySpinBox(self)sb.resize(100, 25)sb.move(100, 100)# ------值的设置与获取-------sb.setValue(20) # 如果设置的数值超过范围,则自动取范围边界值sb.value()if __name__ == "__main__":app = QApplication(sys.argv)window = Window()window.show()sys.exit(app.exec_())
这篇关于PyQt基础_008_ 按钮类控件QSpinbox的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!