如何在Qt模型中插入行,这可能不会发生

How to insert rows in Qt model that may not happen?

本文关键字:Qt 模型 插入      更新时间:2023-10-16

我使用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());
}