How to insert rows in a Qt model that might not happen?

I am using QAbstractItemModel beginInsertRows() and endInsertRows() to insert rows into my data store. I call the data insert function between the begin and end methods. However, the insert function in my data returns a bool parameter, which indicates that the insert may fail due to data limitations. If insertion fails, the model and its associated views should not change. If this happens, how to let the model not insert rows or stop inserting rows?

+4
source share
1 answer

I assume that you are using a custom model that inherits QAbstractItemModel . In this case, you can write an insert method:

 bool CustomModel::insertMyItem(const MyItemStruct &i) { if (alredyHave(i)) return false; beginInsertRow(); m_ItemList.insert(i); endInsertRow(); } 

Your data method would be something like this:

 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(); } 

And finally, your input method will be:

 void MainWindow::input() { MyInputDialog dialog(this); if (dialog.exec() == QDialog::Rejected) return; myModel->insertMyItem(dialog.item()); } 
+3
source

All Articles