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功能?
在这种情况下,最好在模型中保存数据时进行转换:
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)