PyQt窗口部件验证主要有两种:
1.提交后验证,会在用户提交设置数据的时候进行验证
2.预防式验证,会在用户编辑窗口部件就进行验证
本文讲述第二种验证方式,代码如下:
#encoding=utf-8 import sys from PyQt4.QtGui import * from PyQt4.QtCore import * class Set_Number(QDialog): def __init__(self,parent=None): super(Set_Number,self).__init__(parent) #创建正则表达式 punctuationRe = QRegExp(r"[ ,:;.]") thous_label = QLabel('&Thousands separatror') self.thous_line_edit = QLineEdit() #设置最大输入长度 self.thous_line_edit.setMaxLength(1) #使用正则表达式验证器 self.thous_line_edit.setValidator(QRegExpValidator(punctuationRe,self)) thous_label.setBuddy(self.thous_line_edit) decimal_label = QLabel('Decimal &marker') self.decimal_line_edit = QLineEdit() self.decimal_line_edit.setMaxLength(1) self.decimal_line_edit.setValidator(QRegExpValidator(punctuationRe,self)) self.decimal_line_edit.setInputMask("X") decimal_label.setBuddy(self.decimal_line_edit) places_label = QLabel('&Decimal places') self.places_spinbox = QSpinBox() self.places_spinbox.setRange(0,6) places_label.setBuddy(self.places_spinbox) buttonBox = QDialogButtonBox(QDialogButtonBox.Apply | QDialogButtonBox.Cancel) layout = QGridLayout() layout.addWidget(thous_label,0,0) layout.addWidget(self.thous_line_edit,0,1) layout.addWidget(decimal_label,1,0) layout.addWidget(self.decimal_line_edit,1,1) layout.addWidget(places_label,2,0) layout.addWidget(self.places_spinbox,2,1) layout.addWidget(buttonBox,3,1) self.setLayout(layout) self.setWindowTitle('set number format') if __name__ == '__main__': app = QApplication(sys.argv) sn = Set_Number() sn.show() sys.exit(app.exec_())