首页 > 解决方案 > 如何在 QItemDelegate 上应用后期转换?

问题描述

考虑下面的片段:

import sys

from PyQt5.Qt import *  # noqa


class MyCell(QItemDelegate):
    def createEditor(self, parent, option, index):
        w = QLineEdit(parent)
        validator = QRegExpValidator(QRegExp("^$|[0-9A-Fa-f]{1}|[0-9A-Fa-f]{2}|[-]"))
        w.setValidator(validator)

        def convert():
            w.setText(w.text().upper().zfill(2))

        w.returnPressed.connect(convert)

        return w


class MyTable(QTableWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setItemDelegate(MyCell())


if __name__ == "__main__":
    app = QApplication(sys.argv)
    w = MyTable()
    w.setColumnCount(1)
    w.setRowCount(16)
    w.show()
    sys.exit(app.exec_())

您将如何应用转换函数,不仅在发出 returnPressed 信号时,而且在您正在编辑并且突然使用鼠标将焦点切换到另一个项目时?

标签: pythonpyqt5

解决方案


在这种情况下,最好在模型中保存数据时进行转换:

class MyCell(QItemDelegate):
    def createEditor(self, parent, option, index):
        w = QLineEdit(parent)
        validator = QRegExpValidator(QRegExp("[0-9A-Fa-f]{1}|[0-9A-Fa-f]{2}|[-]"))
        w.setValidator(validator)
        return w

    def setModelData(self, editor, model, index):
        text = editor.text().upper().zfill(2)
        model.setData(index, text)

推荐阅读