如何在Qt模型中插入行,这可能不会发生
How to insert rows in Qt model that may not happen?
我使用QAbstractItemModel的beginInsertRows()
和endInsertRows()
将行插入到我的底层数据存储。我在begin和end方法之间调用数据插入函数。然而,我的数据中的插入函数返回一个bool参数,该参数表示插入可能由于数据限制而失败。如果插入失败,则模型及其关联视图不应更改。如果发生这种情况,如何让模型知道不插入行或停止插入行?
我假设,您正在使用继承QAbstractItemModel
的自定义模型。在这种情况下,您可以编写插入方法:
bool CustomModel::insertMyItem(const MyItemStruct &i)
{
if (alredyHave(i))
return false;
beginInsertRow();
m_ItemList.insert(i);
endInsertRow();
}
你的数据方法应该是这样的:
QVariant CustomModel::data(const QModelIndex &index, int role) const
{
if (role == Qt::DisplayRole || role == Qt::ToolTipRole)
switch (index.column())
{
case INDEX_ID:
return m_ItemList[index.row()].id;
case INDEX_NAME:
return m_ItemList[index.row()].name;
...
}
return QVariant();
}
最后,你的输入法是:
void MainWindow::input()
{
MyInputDialog dialog(this);
if (dialog.exec() == QDialog::Rejected)
return;
myModel->insertMyItem(dialog.item());
}
相关文章:
- Qt - QVector 和模型视图 - 从列表视图获取自定义类的最佳方法是什么?
- 如何在Qt中合并/追加/添加两个用于线程的模型?
- Qt创建者-如何删除Clang代码模型
- Qt 模型拖放 - 无法保存类型 QJsonValue
- Qt:模型/视图框架上的数据转换
- Qt 5.2模型视图模式:如何通知模型对象底层数据结构的变化
- Proxies和Fetchmore()/canfetchmore()背后的QT模型()
- Qt:模型/视图-定义项目持有日期的格式
- Qt模型视图:当数据存储和更改数据时,更新模型和视图的正确方法是什么::vector
- 异步 Qt 模型加载到 QML GridView
- Qt模型在单独的线程中查看数据和模型
- 使用具有非类表数据和非表/列表UI的Qt模型/视图
- QT模型/视图,如日志查看器
- Qt模型/视图使用模型项:是特定的视图项所需
- Qt模型视图编程.QAbstractItemModel和QAbstractListModel.Index()和paren
- 如何在Qt模型中插入行,这可能不会发生
- 如何从qt模型中获得所有数据
- Qt模型/视图委托:如何简单地转换文本数据
- 视图的样式表如何与Qt模型/视图环境中模型的::FontRole交互?
- 关于如何使用Qt模型视图类的建议