如何在api v2中重新实现qvalidator.validate()?

时间:2013-07-29 07:19:33

标签: python pyqt qstring

代码在api v1中工作正常,如果我取消注释顶级sip调用,那么这意味着我将使用v2,当然我会看到像

这样的错误

TypeError: invalid result type from Validator.validate()

我知道我需要更改.validate()的返回值,但如果我将其更改为pyqt doc在v2中所说的, http://pyqt.sourceforge.net/Docs/PyQt4/qvalidator.html#validate-2 ,它给我分段错误(在pyqt 4.6.1,centos 6.3 x64)。为什么呢?

v2代码在pyqt 4.8和4.10上工作正常(在fedora 19 linux和Windows 7机器上测试。)这是一个错误还是我错过了什么?

谢谢!

#!/usr/bin/env python2

# api v2
import sip
sip.setapi('QString', 2)
sip.setapi('QVariant', 2)

from PyQt4.QtGui import *
from PyQt4.QtCore import *
import re,os,sys

class MyQComboBox(QComboBox):
    def __init__(self, parent=None, listing=None):
        super(MyQComboBox, self).__init__(parent)

        if listing != None:
            self.listSetup(listing)

    def listSetup(self, listing):
        self.setEditable(True)

        self.listing = listing
        self.clear()
        self.addItems(self.listing)

        self.completer = QCompleter(self.listing)
        self.setCompleter(self.completer)

        self.valid = QValidator_listValid(self, listing = self.listing)  
        self.setValidator(self.valid)


# api v1
# class QValidator_listValid(QValidator):
#     def __init__(self, parent=None, listing=None):
#         super(QValidator_listValid, self).__init__(parent)
#         self.listing = listing

#     def validate(self, input, pos=None):
#         for name in self.listing:
#             if re.match(str(input), name, re.I):
#                 return (QValidator.Acceptable, pos)
#         return (QValidator.Invalid, pos)

# api v2
class QValidator_listValid(QValidator):
    def __init__(self, parent=None, listing=None):
        super(QValidator_listValid, self).__init__(parent)
        self.listing = listing

    def validate(self, input, pos=None):
        for name in self.listing:
            if re.match(input, name, re.I):
                return (QValidator.Acceptable,input, pos)
        return (QValidator.Invalid,input,pos)

if __name__ == "__main__":
    app = QApplication(sys.argv)

    ui = MyQComboBox()
    ui.listSetup(['aaa','bbb','ccc'])
    ui.show()
    sys.exit(app.exec_())

1 个答案:

答案 0 :(得分:0)

我不是专家,但也许这有帮助:

class MetaNameLineEdit(QtGui.QLineEdit):
    Prefix = 'New_'
    Pattern = '^{prefix}([A-Za-z0-9_]{{0,{n}}})$'.format(prefix=Prefix, n=50)

    def __init__(self, parent):
        QtGui.QLineEdit.__init__(self, parent)
        self.setValidator(QtGui.QRegExpValidator(QtCore.QRegExp(self.Pattern), self))