import sys from PyQt5.Qt import * class CAbstractSpinBox(QAbstractSpinBox): def __init__(self, parent=None): super(CAbstractSpinBox, self).__init__(parent) self.flag = False def stepEnabled(self): # 如果文本框中的内容可以转为整形 try: text = int(self.text()) # 否则可判断为文本框为空。主要针对首次运行,无输入,验证及修复未执行,直接点击步长按钮的情况 except: self.lineEdit().setText("1") self.flag = True return QAbstractSpinBox.StepNone else: if 1 < text < 9: return QAbstractSpinBox.StepUpEnabled | QAbstractSpinBox.StepDownEnabled elif text == 1: return QAbstractSpinBox.StepUpEnabled elif text == 9: return QAbstractSpinBox.StepDownEnabled else: return QAbstractSpinBox.StepNone def stepBy(self, steps: int) -> None: text = int(self.text()) + steps self.lineEdit().setText(str(text)) def validate(self, input: str, pos: int): if len(input) == 0: return (QValidator.Intermediate, input, pos) else: try: input = int(input) except: return (QValidator.Invalid, input, pos) else: if 1 <= input <= 9: return (QValidator.Acceptable, str(input), pos) elif input < 1 or input > 9: return (QValidator.Invalid, str(input), pos) def fixup(self, input: str) -> str: return "1" class Window(QWidget): def __init__(self): super().__init__() self.setup_ui() def setup_ui(self): self.setWindowTitle("Qt桌面应用程序") self.resize(300, 300) self.abstract_spin_box = CAbstractSpinBox(self) self.abstract_spin_box.resize(50, 30) self.abstract_spin_box.move(50, 50) if __name__ == '__main__': app = QApplication(sys.argv) window = Window() window.show() sys.exit(app.exec_())