【发布时间】:2014-12-06 13:40:38
【问题描述】:
我有从 QAbstractTableModel 继承的 C++ 类,并覆盖了下一个函数:
virtual QHash<int, QByteArray> roleNames() const noexcept override;
virtual Qt::ItemFlags flags(const QModelIndex& index) const noexcept override;
virtual int rowCount(const QModelIndex& parent = QModelIndex()) const noexcept override;
virtual int columnCount(const QModelIndex& parent = QModelIndex()) const noexcept override;
virtual QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const noexcept override;
virtual bool removeRows(int row, int count, const QModelIndex& parent = QModelIndex()) noexcept override;
virtual bool insertRows(int row, int count, const QModelIndex& parent = QModelIndex()) noexcept override;
virtual bool setData(const QModelIndex& index, const QVariant& data, int role = Qt::EditRole) noexcept override;
model有3列,第一个是只读的,最后一个是可编辑的,所以这是flags()方法的实现:
Qt::ItemFlags ObjectInitialStateModel::flags(const QModelIndex& index) const noexcept
{
if (index.column() == 0)
{
return Qt::ItemIsEnabled | Qt::ItemNeverHasChildren;
}
else
{
return Qt::ItemIsEnabled | Qt::ItemIsEditable | Qt::ItemNeverHasChildren;
}
}
在 QML 部分模型显示正常,但我不知道如何在 TableView 中编辑 2 和 3 列的模型数据。我试过写列委托:
Item {
id: item
state: "labelMode"
Text {
id: textLabel
text: styleData.value
anchors.fill: parent
renderType: Text.NativeRendering
}
TextField {
id: textField
text: styleData.value
anchors.fill: parent
Keys.onEnterPressed: commit()
Keys.onReturnPressed: commit()
Keys.onEscapePressed: rollback()
function commit() {
item.state = "labelMode"
}
function rollback() {
item.state = "labelMode"
}
}
MouseArea {
id: mouseArea
anchors.fill: parent
onDoubleClicked: item.state = "editMode"
}
states: [
State {
name: "labelMode"
PropertyChanges {
target: textLabel
visible: true
}
PropertyChanges {
target: mouseArea
visible: true
}
PropertyChanges {
target: textField
visible: false
}
},
State {
name: "editMode"
PropertyChanges {
target: textLabel
visible: false
}
PropertyChanges {
target: mouseArea
visible: false
}
PropertyChanges {
target: textField
visible: true
focus: true
}
}
]
}
但我不知道如何在 commit() 函数中正确地为模型设置新数据。 或者可能有另一种在 QML 中使用可编辑列和 C++ 模型实现表的正确方法?
【问题讨论】: