代码之家  ›  专栏  ›  技术社区  ›  BPL

如何在QItemDelegate上应用后转换?

  •  0
  • BPL  · 技术社区  · 5 年前

    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信号时,以及在编辑时突然使用鼠标将焦点切换到另一个项目时,您将如何应用convert功能?

    1 回复  |  直到 5 年前
        1
  •  1
  •   eyllanesc    5 年前

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

    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)