[英]How to get QModelIndex to insert a new row in a QAbstractTableModel?
我第一次使用模型/視圖編程,因為需要組合框,所以將表視圖與QAbstractTableModel
和QStyledItemDelegate
一起使用。 這是我的模型:
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.