问题描述
我正在尝试创建一个自定义委托,以便我可以使用 Regex 来验证输入到表中的数据,但由于某种原因,我的代码不断抛出错误,是否有一个好的结构化示例?
I'm trying to create a custom delegate so I can use Regex to verify the data that's being entered into the table but for some reason, my code keeps throwing errors, is there a good structured example?
这是我目前遇到的两个错误,当我使用 QLineEdit.setText 修复 AttributeError: 'QLineEdit' object has no attribute 'set'
时,我的正则表达式不起作用它允许添加任何值.
These are the two errors I'm currently getting, and when I fix the AttributeError: 'QLineEdit' object has no attribute 'set'
by using QLineEdit.setText my regular expression doesn't work and it allows any value to be added in.
Traceback (most recent call last):
File "F:\Computing\Program V3\stockGui.py", line 23, in setEditorData
editor.set(text)
AttributeError: 'QLineEdit' object has no attribute 'set'
Traceback (most recent call last):
File "F:\Computing\Program V3\stockGui.py", line 29, in setModelData
model.setData(index, QVariant(editor.text()))
NameError: name 'QVariant' is not defined
class ProductDelegate(QtSql.QSqlRelationalDelegate):
def __init__(self):
super().__init__()
def createEditor(self, parent, option, index):
if index.column() == 1:
editor = QtGui.QLineEdit(parent)
regex = QtCore.QRegExp(r"(?:[A-Z|\s]+)")
validator = QtGui.QRegExpValidator(regex,parent)
editor.setValidator(validator)
return editor
else:
return QtSql.QSqlRelationalDelegate.createEditor(self, parent, option, index)
def setEditorData(self, editor, index):
if index.column() == 1:
text = index.model().data(index, QtCore.Qt.DisplayRole)
editor.set(text)
else:
QtSql.QSqlRelationalDelegate.setEditorData(self, editor,index)
def setModelData(self, editor, model, index):
if index.column() == 1:
model.setData(index, QVariant(editor.text()))
else:
QtSql.QSqlRelationalDelegate.setModelData(self, editor, model, index)
推荐答案
正如您所发现的,setText
不进行任何验证.因此,请改用 insert:
As you've discovered, setText
doesn't do any validatation. So, instead, use insert:
text = index.model().data(index, QtCore.Qt.DisplayRole)
editor.clear()
editor.insert(text)
另一个错误是因为你没有导入QVariant
,所以你不能使用它.最简单的解决方法是完全省略它(PyQt 会在合适的地方自动将参数转换为 QVariant
):
The other error is caused simply because you did not import QVariant
, and so you can't use it. The easiest fix is to just omit it altogether (PyQt will automatically convert to arguments to a QVariant
wherever it's appropriate):
model.setData(index, editor.text())
(注意:如果您使用的是 Python 3,那么默认情况下,QVariant
总是自动转换为等效的 Python 类型或从等效的 Python 类型转换).
(NB: if you're using Python 3, then, by default, QVariant
is always automatically converted both to and from the equivalent Python types).
这篇关于带有正则表达式的自定义 QAbstractItemDelegate 用于 QSqlTableModel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!