PyQt基础_008_ 按钮类控件QSpinbox

基本操作

PyQt基础_008_ 按钮类控件QSpinbox_第1张图片

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_())

长按加速

PyQt基础_008_ 按钮类控件QSpinbox_第2张图片

import sys

from PyQt5.Qt import *

class MyASB(QAbstractSpinBox):
    def __init__(self, parent, num: int = 0):
        super().__init__(parent)
        self.current_num = 0
        self.lineEdit().setText(f"{num}")

    def stepEnabled(self) -> "QAbstractSpinBox.StepEnabled":
        return QAbstractSpinBox.StepUpEnabled | QAbstractSpinBox.StepDownEnabled

    def stepBy(self, steps: int) -> None:
        self.current_num = self.current_num + steps
        self.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_())

自定义形状

PyQt基础_008_ 按钮类控件QSpinbox_第3张图片

import sys

from 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,pyqt)