导言
该案例所含的独立视窗类,包括了不同选择的行编辑,该选择有限制输入和显示属性,这可以通过复合框中的项进行选择更改。集中体现这些,是为了帮助开发者选择适合的属性用于行编辑,并使得容易比较每种用户输入验证的效果。
定义窗口类
Window类继承自QWidget,包含一个构造器和一些槽,当在符合框内选择一个新的验证器时,这些槽用于更新其类型。Window构造器用于设置行编辑、验证器和复合框,将复合框信号链接到类中的槽,并在布局中排列子部件。我们开始创建一个容纳标签的组合框、复合框和行编辑,这样我们就能演示QLineEdit.echoMode属性。
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
import sys
class Window(QWidget):
def __init__(self):
super(Window, self).__init__()
self.echoGroup = QGroupBox('Echo')
self.echoLabel = QLabel('Mode:')
self.echoComboBox = QComboBox()
self.echoComboBox.addItem('Normal')
self.echoComboBox.addItem('Password')
self.echoComboBox.addItem('PasswordEchoOnEdit')
self.echoComboBox.addItem('No Echo')
self.echoLineEdit = QLineEdit()
self.echoLineEdit.setPlaceholderText('Placeholder Text')
self.echoLineEdit.setFocus()
- 这里所有的部件都没有排列到布局,最终echoLabel、echoComboBox和echoLineEdit会放置到echoGroup的垂直布局。
下面我们构建组合框,并构建体现行编辑内容的QIntValidator和QDoubleValidator显示效果的部件集合。
self.validatorGroup = QGroupBox('Validator')
self.validatorLabel = QLabel('Type:')
self.validatorComboBox = QComboBox()
self.validatorComboBox.addItem('No validator')
self.validatorComboBox.addItem('Integer validator')
self.validatorComboBox.addItem('Double validator')
self.validatorLineEdit = QLineEdit()
self.validatorLineEdit.setPlaceholderText('Placeholder Text')
文本对齐方式通过其他部件组演示
self.alignmentGroup = QGroupBox('Alignment')
self.alignmentLabel = QLabel('Type:')
self.alignmentComboBox = QComboBox()
self.alignmentComboBox.addItem('Left')
self.alignmentComboBox.addItem('Centered')
self.alignmentComboBox.addItem('Right')
self.alignmentLineEdit = QLineEdit()
self.alignmentLineEdit.setPlaceholderText('Placeholder Text')
QLineEdit支持输入模板的使用,这只允许用户根据规范输入字符。我们构建一个部件组来演示预定义模板的选项。
self.inputMaskGroup = QGroupBox('Input mask')
self.inputMaskLabel = QLabel('Type:')
self.inputMaskComboBox = QComboBox()
self.inputMaskComboBox.addItem('No mask')
self.inputMaskComboBox.addItem('Phone number')
self.inputMaskComboBox.addItem('ISO date')
self.inputMaskComboBox.addItem('License key')
self.inputMaskLineEdit = QLineEdit()
self.inputMaskLineEdit.setPlaceholderText('Placeholder Text')
QLineEdit其他有用的特性是可以设置它的内容为只读。
self.accessGroup = QGroupBox('Access')
self.accessLabel = QLabel('Read-only:')
self.accessComboBox = QComboBox()
self.accessComboBox.addItem('False')
self.accessComboBox.addItem('True')
self.accessLineEdit = QLineEdit()
self.accessLineEdit.setPlaceholderText('Placeholder Text')
现在,所有的子部件构建完毕,我们将复合框的信号连接到Window对象。
self.echoComboBox.activated.connect(self.echoChanged)
self.validatorComboBox.activated.connect(self.validatorChanged)
self.alignmentComboBox.activated.connect(self.alignmentChanged)
self.inputMaskComboBox.activated.connect(self.inputMaskChanged)
self.accessComboBox.ac