1
votes

When entering a QTableWidget in the third to eighth column, I only want to allow integers and decimal numbers with three decimal places. Have tried various things:

self.vg.tablewidget.setValidator(QRegExpValidator(QRegExp("[0-9]*[.]{,1}[0-9]{,3}"))) or
self.vg.tableWidget.setItemDelegateForColumn(2, QRegularExpressionValidator(("[0-9]*[.]{,1}[0-9]{,3}"))).

Unfortunately without success.

1

1 Answers

0
votes

You have to create a class that inherits from QStyledItemDelegate or QItemDelegate and override the createEditor method where you set the QValidator in the editor.

class StyledItemDelegate(QtWidgets.QStyledItemDelegate):
    def createEditor(self, parent, option, index):
        editor = super().createEditor(parent, option, index)
        if isinstance(editor, QtWidgets.QLineEdit):
            validator = QtGui.QRegExpValidator(
                QtCore.QRegExp(r"[0-9]*[.]{,1}[0-9]{,3}"), editor
            )
            editor.setValidator(validator)
        return editor
for i in range(3, 9):
    delegate = StyledItemDelegate(self.vg.tableWidget)
    self.vg.tableWidget.setItemDelegateForColumn(i, delegate)