c++ - 如何让 QModelIndex 在 QAbstractTableModel 中插入新行?

标签 c++ qt

我是第一次使用模型/ View 编程,我使用的是 TableView 以及 QAbstractTableModelQStyledItemDelegate,因为我需要组合框。 这是我的模型:

class STableModel : public QAbstractTableModel
{
   Q_OBJECT

   public:
    STableModel(int rows = 1, int columns = 1, QObject *parent = 0);

    int rowCount(const QModelIndex &parent = QModelIndex()) const;
    int columnCount(const QModelIndex &parent = QModelIndex()) const;
    QVariant data(const QModelIndex &index, int role) const;
    QVariant headerData(int section, Qt::Orientation orientation,
                    int role = Qt::DisplayRole) const;

    Qt::ItemFlags flags(const QModelIndex &index) const;
    bool setData(const QModelIndex &index, const QVariant &value,
         int role = Qt::EditRole);

    bool insertRows(int position, int rows, const QModelIndex &parent = QModelIndex());
    bool insertColumns(int position, int columns, const QModelIndex &parent = QModelIndex());
    bool removeRows(int position, int rows, const QModelIndex &parent = QModelIndex());
    bool removeColumns(int position, int columns, const QModelIndex &parent = QModelIndex());

   private:
    QList<QStringList> rowList;
    ComboBoxItemDelegate *myDelegate;
};    

在这里,我试图在我的模型中添加一个新行,但应用程序崩溃了,我认为它崩溃是因为索引无效。

   STableModel *model; = new STableModel(1, 1, this);
   QModelIndex index = model->index(1, 1, QModelIndex());
   model->insertRows(1, 4, index);

如何在此处获得正确的索引或指导我使用其他方法添加行。谢谢

编辑:

bool STableModel::insertRows(int position, int rows, const QModelIndex &parent)
{
    int columns = columnCount();
    beginInsertRows(parent, position, position + rows - 1);

    for (int row = 0; row < rows; ++row) {
        QStringList items;
        for (int column = 0; column < columns; ++column)
            items.append("");
        rowList.insert(position, items);
    }

    endInsertRows();
    return true;
}

最佳答案

model->index(1, 1, QModelIndex()); 返回无效索引,因为没有坐标为 [1, 1] 的索引。
您可以删除此行,您不需要此表的父索引。

根据提供的信息,我无法说出 index() 方法崩溃的原因。它不应该,即使提供了无效的行号和列号。

关于c++ - 如何让 QModelIndex 在 QAbstractTableModel 中插入新行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35032728/

相关文章:

c++ - 如何在 C++/MFC 中将二进制数据编码为文本?

C++ 创建空字节

Qt QString maxsplit 参数

c++ - OpenGL + SDL 有时会脱离坐标

c++ - 如何查询 Internet Explorer 版本以便它也适用于 IE10?

c++ - 在 win7-64bit msvc2010 上构建 Qt 5.4.0 并且每次都失败

python - 仅具有年/月 View 的 PyQt 日历

c++ - 如何获取指向 Qt 容器中原始数据的指针?

c++ - 普通堆栈实现中的内存泄漏

c++ - C++中二维 vector 的列大小和行大小