c++ - QTableView:从模型中删除行 -> 空行和 "QSortFilterProxyModel: index from wrong model passed to mapFromSource"

标签 c++ qt viewmodel qtableview qsortfilterproxymodel

我正在尝试实现一个 qTableView 结构。

这是我的部分代码:

m_model = new PatientModel(this); //This is my QAbstractTableModel subclass
m_proxy = new QSortFilterProxyModel(this);
m_proxy->setSourceModel(m_model);

要追加一行我说(我想显示患者对象):

void PatientModel::append(Patient* patient) {
   beginInsertRows(QModelIndex(), m_data.count(), m_data.count());
        m_data.append(patient);
   endInsertRows();
}

效果很好。该行被添加到 View 和数据中(m_data 是一个 QList 的

为了删除一行,我尝试了几种方法,目前我有这个

bool PatientModel::removeRows(int row, int count, const QModelIndex &parent)
{
    Q_UNUSED(parent);
    this->layoutAboutToBeChanged();
    beginRemoveRows(QModelIndex(), row, row+count-1);
        m_data.removeAt(row);
    endInsertRows();
    this->layoutChanged(); //force refresh, keine Ahnung

    return true;
}

经过一些研究,我添加了 layoutAboutTobeChanged() 和 layoutChanged()。在添加这两行之前,删除后有一个空行。现在没有了,但是当我删除第 3 行时,我不能先点击第 3+ 行,否则应用程序将崩溃并显示以下错误消息:

QSortFilterProxyModel: index from wrong model passed to mapFromSource
Segmentation fault: 11

我做错了什么吗?

提前致谢!

最佳答案

没关系,我想我做错了什么。将 RemoveRows 更改为此,现在可以使用了:

bool PatientModel::removeRows(int row, int count, const QModelIndex &parent)
{
    Q_UNUSED(parent);
    beginRemoveRows(QModelIndex(), row, row+count-1);
     for (int i=0; i < count; ++i) {
         m_data.removeAt(row);
     }
     endRemoveRows();

    return true;
}

关于c++ - QTableView:从模型中删除行 -> 空行和 "QSortFilterProxyModel: index from wrong model passed to mapFromSource",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53430734/

相关文章:

c++ - 如何在 OpenBR 中运行 C++ 文件?

c++ - 从 QFileSystemModel 中的文件路径和文件名获取 QModelIndex

mvvm - 用于添加和编辑的多个ViewModel(WPF,MVVM)

apache-flex - 避免 View 模型中的重复数据和计算

c++ - 工厂方法中的访问冲突

c++ - 尝试在 OpenSSL 中使用 EVP 函数时出现段错误

c++ - 你怎么称呼这个模板构造函数?

c++ - char 到 int 的转换 - 这里发生了什么?

c# - C# 中的 MVVM 存储状态

Android Hello World Qt 5.2