Reputation: 5
How do I implement input validation in each cells? I want the input to be integers that fall within the range of 0 and 100
Upvotes: 0
Views: 316
Reputation: 243887
One option is to set a QIntValidator to the editor created by the delegate:
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
class Delegate(QtWidgets.QStyledItemDelegate):
def createEditor(self, parent, option, index):
editor = super().createEditor(parent, option, index)
if isinstance(editor, QtWidgets.QLineEdit):
validator = QtGui.QIntValidator(0, 100, editor)
editor.setValidator(validator)
return editor
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
table_widget = QtWidgets.QTableWidget(10, 4)
table_widget.resize(640, 480)
table_widget.show()
delegate = Delegate()
table_widget.setItemDelegate(delegate)
app.exec_()
Another option is to use a QSpinBox as an editor that already has a validator.
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
class Delegate(QtWidgets.QStyledItemDelegate):
def createEditor(self, parent, option, index):
return QtWidgets.QSpinBox(parent, minimum=0, maximum=100)
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
table_widget = QtWidgets.QTableWidget(10, 4)
table_widget.resize(640, 480)
table_widget.show()
delegate = Delegate()
table_widget.setItemDelegate(delegate)
app.exec_()
Upvotes: 1