如何验证 QTableWidget 中的单元格? [英] How validate a cell in QTableWidget?

查看:80
本文介绍了如何验证 QTableWidget 中的单元格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 python3.4 中工作 eith pyqt4 我想验证单元格中的文本在引入时是否为浮点数.我该怎么做?

I work eith pyqt4 in python3.4 I want to validate if the text in the cell is a float number when it is introduced. How I do that?

推荐答案

您有两个选择.

您可以创建一个 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)

这篇关于如何验证 QTableWidget 中的单元格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆