编写一个QTableView的delegate,该delegate的数据类型为自定义类型
时间: 2024-02-17 14:01:59 浏览: 105
好的,我可以为您提供一个简单的示例。假设您有一个名为`CustomData`的自定义数据类型,它有两个属性:`name`和`age`。
首先,您需要编写一个自定义的Delegate类,该类继承自QItemDelegate,并且需要重写createEditor()、setEditorData()、setModelData()和updateEditorGeometry()方法。
```python
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QIntValidator
from PyQt5.QtWidgets import QItemDelegate, QLineEdit
class CustomDelegate(QItemDelegate):
def createEditor(self, parent, option, index):
editor = QLineEdit(parent)
validator = QIntValidator(0, 100, editor)
editor.setValidator(validator)
return editor
def setEditorData(self, editor, index):
value = index.model().data(index, Qt.EditRole)
editor.setText(str(value.age))
def setModelData(self, editor, model, index):
value = model.data(index, Qt.EditRole)
value.age = int(editor.text())
model.setData(index, value, Qt.EditRole)
def updateEditorGeometry(self, editor, option, index):
editor.setGeometry(option.rect)
```
然后,您需要在使用QTableView时将该Delegate应用于您的模型。例如:
```python
from PyQt5.QtCore import Qt, QAbstractTableModel, QVariant, QModelIndex
from PyQt5.QtWidgets import QTableView, QApplication
class CustomData:
def __init__(self, name, age):
self.name = name
self.age = age
class CustomTableModel(QAbstractTableModel):
def __init__(self, data):
super().__init__()
self._data = data
def data(self, index, role=Qt.DisplayRole):
if role == Qt.DisplayRole:
if index.column() == 0:
return self._data[index.row()].name
elif index.column() == 1:
return self._data[index.row()].age
elif role == Qt.EditRole:
return self._data[index.row()]
def setData(self, index, value, role=Qt.EditRole):
if role == Qt.EditRole:
self._data[index.row()] = value
self.dataChanged.emit(index, index)
return True
return False
def rowCount(self, parent=QModelIndex()):
return len(self._data)
def columnCount(self, parent=QModelIndex()):
return 2
def headerData(self, section, orientation, role=Qt.DisplayRole):
if role == Qt.DisplayRole and orientation == Qt.Horizontal:
if section == 0:
return "Name"
elif section == 1:
return "Age"
return QVariant()
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
data = [CustomData("Tom", 20), CustomData("Jerry", 30), CustomData("Lucy", 25)]
model = CustomTableModel(data)
view = QTableView()
view.setModel(model)
delegate = CustomDelegate(view)
view.setItemDelegate(delegate)
view.show()
sys.exit(app.exec_())
```
这样,当您在TableView中编辑一行时,Delegate会将其转换为CustomData类型,并将其存储到Model中。
阅读全文