python - 如何在 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 信号时,而且在您正在编辑并且突然使用鼠标将焦点切换到另一个项目时?
解决方案
在这种情况下,最好在模型中保存数据时进行转换:
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)
推荐阅读
- python - Python监控多部分表单上传的进度
- java - java.lang.IllegalStateException: [TextView] 不能为空
- django - 如何更改 Django 管理面板登录表单要求
- autodesk-forge - 访问令牌给出以下错误消息加载资源失败:服务器响应状态为 500
- reactjs - 如何将字符串传递给solidity的setter函数?
- node.js - 如何从 PowerShell 脚本执行 NPM 命令
- amazon-web-services - AWS CloudFront + 单个 S3 存储桶 + xyz.cloudfront.net 上的多个子域
- c# - C# - 设置 HttpClient 标头以将数据发布到 Azure REST API
- git - Gitflow、工件版本和拉取请求
- python - 从元组列表中获取其元素之间差异最大的元组