侧边栏壁纸
博主头像
996worker

祇園精舎の鐘の聲, 諸行無常の響き有り。

  • 累计撰写 189 篇文章
  • 累计创建 46 个标签
  • 累计收到 8 条评论

目 录CONTENT

文章目录

Pyqt5 QTableWidgetItem only takes numeric inputs

996worker
2022-05-01 / 0 评论 / 0 点赞 / 84 阅读 / 1,012 字
温馨提示:
本文最后更新于 2022-05-01,若内容或图片失效,请留言反馈。部分素材来自网络,若不小心影响到您的利益,请联系我们删除。

Requirement

We have a QTableWidget, and several rows can only take numeric inputs, for example:

image

Solution

Use a Helper Delegate Class:

class NumericDelegate(QStyledItemDelegate):
    """
    Delegate class to only take number input for table view
    """
    def createEditor(self, parent, option, index):
        editor = super(NumericDelegate, self).createEditor(parent, option, index)
        if isinstance(editor, QLineEdit):
            reg_ex = QRegExp("[0-9]+.?[0-9]{,12}")
            validator = QRegExpValidator(reg_ex, editor)
            editor.setValidator(validator)
        return editor

Then use it in the row you needed:

# value column
            type_text = metadata_dict['type'].lower()
            if type_text == NUMBER_METADATA_TYPE:
                value_item = QTableWidgetItem('0')

                # set item only take numerical inputs
                num_input_delegate = NumericDelegate(self.__ui.metadataTableWidget)
                self.__ui.metadataTableWidget.setItemDelegateForRow(i, num_input_delegate)

            else:
                value_item = QTableWidgetItem('none')

            value_item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable | Qt.ItemIsEditable)
            self.__ui.metadataTableWidget.setItem(i, 1, value_item)
0

评论区