【问题标题】:PyQt QWizard validation and button overridePyQt QWizard 验证和按钮覆盖
【发布时间】:2015-01-01 15:08:22
【问题描述】:

我有一个多页 QWizard,我需要在其中对数字输入进行一些验证。多个 QLineEdit 小部件可以包含任何浮点类型或字符串“None”,其中“None”是 sqlite 中 REAL 列的默认空值。 QValidator 可以验证浮点部分,但是当它在您键入时验证它不适合评估“无”字符串(例如,用户可以输入 NNNooo)。对每个 QLineEdit 失去焦点的验证也不合适,因为用户在移动到下一页之前可能不会选择每个 QLE。我能想到的就是通过覆盖/拦截下一个按钮调用来验证所有字段。在 QWizard 页面中,我可以断开下一个按钮(无法使新样式断开连接):

self.disconnect(self.button(QWizard.NextButton), QtCore.SIGNAL('clicked()'), self, QtCore.SLOT('next()'))
self.button(QWizard.NextButton).clicked.connect(self.validateOnNext)

在 QWizardPages 里面 init 我可以连接到下一个按钮(新样式):

self.parent().button(QWizard.NextButton).clicked.connect(self.nextButtonClicked) 

但是断开 QWizard 的下一个插槽不起作用(2 种方式):

self.parent().button(QWizard.NextButton).clicked.disconnect(self.next) 

我得到一个 AttributeError: 'MyWizardPage' 对象没有属性 'next'

self.parent().disconnect(self.parent().button(QWizard.NextButton), QtCore.SIGNAL('clicked()'), self, QtCore.SLOT('next()'))

我没有收到任何错误,但下一个按钮仍然有效

每个 QWizardPage 连接到 'next' 插槽的问题是,每个页面中的 init 方法都是在向导启动期间执行的 - 所以当按下 next 时,所有向导页面的 nextButtonClicked() 方法都会执行。也许我可以禁用 QWizardPage onFocus() 上的所有下一个功能,实现它自己的下一个功能,并对每个页面执行相同操作,但似乎过于复杂

原本简单的验证问题现在变成了信号/插槽拦截器问题。有什么想法吗?

【问题讨论】:

    标签: python qt validation pyqt pyqt4


    【解决方案1】:

    您可以轻松创建自己的接受自定义值的验证器子类。您需要做的就是重新实现其validate 方法。

    这是一个使用QDoubleValidator的简单示例:

    from PyQt4 import QtCore, QtGui
    
    class Validator(QtGui.QDoubleValidator):
        def validate(self, value, pos):
            text = value.strip().title()
            for null in ('None', 'Null', 'Nothing'):
                if text == null:
                    return QtGui.QValidator.Acceptable, text, pos
                if null.startswith(text):
                    return QtGui.QValidator.Intermediate, text, pos
            return super(Validator, self).validate(value, pos)
    
    class Window(QtGui.QWidget):
        def __init__(self):
            super(Window, self).__init__()
            self.edit = QtGui.QLineEdit(self)
            self.edit.setValidator(Validator(self.edit))
            layout = QtGui.QVBoxLayout(self)
            layout.addWidget(self.edit)
    
    if __name__ == '__main__':
    
        import sys
        app = QtGui.QApplication(sys.argv)
        window = Window()
        window.setGeometry(500, 300, 200, 50)
        window.show()
        sys.exit(app.exec_())
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-10
      • 1970-01-01
      • 2010-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-14
      • 1970-01-01
      相关资源
      最近更新 更多