且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何验证 QTableWidget 中的单元格?

更新时间:2023-09-06 17:46:04

您有两个选择.

您可以创建一个 QItemDelegate 并覆盖 createEditorsetEditorDatasetModelData 来控制它们的小部件重新提交以编辑数据.如果您愿意,您可以使用验证器创建 QLineEdit,但如果它们只能输入一个数字,您可能应该只使用 QSpinBoxQDoubleSpinBox,只允许整数和浮点数.或者,您可以让他们输入他们想要的任何内容,然后在 setModelData 函数中忽略任何输入的不是有效数字的值.

You can create a QItemDelegate and override the createEditor, setEditorData and setModelData to control the widget they're presented with to edit the data. You can create a QLineEdit with a validator if you'd like, but if they can only enter a number, you should probably just use a QSpinBox or QDoubleSpinBox, which only allow integers and floats. Alternatively, you could let them enter whatever they want and then in the setModelData function just ignore any entered values that aren't valid numbers.

class MyDelegate(QtGui.QItemDelegate):

    def createEditor(self, parent, option, index):
        return QtGui.QSpinBox(parent)


delegate = MyDelegate()
table.setItemDelegate(delegate)

或者,如果您的表中的项目已经有数字,那么稍微简单一点的解决方案,只需为该项目的 EditData 角色分配一个整数或浮点数.Qt 会注意到类的类型并自动为你构造一个 QSpinBoxQDoubleSpinBox.

Or, a slightly easier solution if the items in your table already have numbers, just assign an integer or float to the EditData role for the item. Qt will notice the class type and automatically construct a QSpinBox or QDoubleSpinBox for you.

item = QTableWidgetItem()
item.setData(QtCore.Qt.EditRole, 5)