【发布时间】:2020-03-19 11:29:34
【问题描述】:
所以,我有一个 QAbstractList 模型 - ContactBookModel。模型元素由Contact 类表示,该类包含构造函数以及name 和number 字段。
它有效,但只能查看,我无法编辑它。
然后我添加了这个方法:
Q_INVOKABLE bool add(const QString& name, const QString& number);
如果您需要实施:
bool ContactBookModel::add(const QString& name, const QString& number)
{
try
{
if(name.isEmpty() || number.isEmpty())
{
return false;
}
beginInsertRows(QModelIndex(), rowCount(), rowCount());
contacts.append(Contact(name, number));
endInsertRows();
return true;
}
catch(std::exception& e)
{
return false;
}
}
这行得通,我从 QML 调用此方法,并从 TextFields 传递 2 个字符串作为参数。
但是文档说我需要重新实现insertRow() 方法。
好的,应该是这样的:
bool ContactBookModel::insertRow(int row, const QModelIndex &parent = QModelIndex())
{
beginInsertRows(parent, row, row+1);
contacts.append(/*what should be here?*/); //contacts is a private field in a ContactBookModel. They have got a QList<Contact> type.
endInsertRows();
}
1) 如您所见,当我使用 add 时,我在方法中构造了 Contact,使用两个字段。 insertRow() 怎么办?在哪里获得(构造)Contact?
2) 如何删除联系人?文档说我应该重新实现removeRow()。如何在 QML 中使用它?
3) 如何从 QML 编辑联系人?
完整的项目代码在这里: https://github.com/bogdasar1985/ContactBook
【问题讨论】: