c++ - 如何在 Qt 模型中插入可能不会发生的行?

标签 c++ qt

我正在使用 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/

相关文章:

c++ - 在 Qt 中声明元类型的问题

c++ - QString& 和 QString & 有区别吗?

QTimer::singleShot 和 QMetaMethod::invoke

c++ - 参照同一 vector 的数据插入 vector

c++ - 构造函数从文件中读取并存储在链表中

C++ - 对`vtable 的 undefined reference

c++ - glDrawElements 崩溃(OpenGL 3.2/Windows 7)

c++ - 替换表的列值(如果存在)

qt - 如何解决(不兼容的发送方/接收方参数)问题?

c++ - 如何设置 QNetworkReply 属性以获得正确的 NCBI 页面?