繁体   English   中英

如何获取QModelIndex以在QAbstractTableModel中插入新行?

[英]How to get QModelIndex to insert a new row in a QAbstractTableModel?

我第一次使用模型/视图编程,因为需要组合框,所以将表视图与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()方法崩溃的原因。 即使提供了无效的行号和列号,也不应这样做。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM