我正在使用 QAbstractItemModel 的 beginInsertRows()
和 endInsertRows()
将行插入到我的底层数据存储中。我在开始和结束方法之间调用数据插入函数。但是,我的数据中的插入函数返回一个 bool 参数,该参数指示插入可能由于数据限制而失败。如果插入失败,模型及其关联的 View 不应更改。如果发生这种情况,如何让模型知道不插入行或停止插入行?
最佳答案
我假设您使用的是自定义模型,它继承了 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());
}
关于c++ - 如何在 Qt 模型中插入可能不会发生的行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15850419/