hello everyone,

yesterday, i wrote a test programe using QTableView. i define class CustomModel inheriting from QAbstractTableModel , which implemented rowCount, columnCount, data and headerData. the CustomModel has a member customs storing the data, its a QList. i add a button to add one item to the data.

But when i click the button, the view shows tow columns, one is the item i add, the other is a blank row.

i can't solve it, thanks for your help!

its the initial state
qt1.png

when i click once
qt2.png

when i click twice
qt3.png

CustomModel definition
Qt Code:
  1. struct Custom{
  2. Custom();
  3. QString col1;
  4. QString col2;
  5. QString col3;
  6. QString col4;
  7. };
  8.  
  9. class CustomModel : public QAbstractTableModel{
  10. Q_OBJECT
  11. public:
  12. CustomModel(QObject* parent = 0);
  13. ~CustomModel();
  14. int rowCount(const QModelIndex &parent) const;
  15. int columnCount(const QModelIndex &parent) const;
  16. QVariant data(const QModelIndex &index, int role) const;
  17. QVariant headerData(int section, Qt::Orientation orientation, int role) const;
  18. bool appendCustom(Custom* custom, const QModelIndex &parent = QModelIndex());
  19. private:
  20. QList<Custom*> customs;
  21. };
To copy to clipboard, switch view to plain text mode 
CustomModel::appendCustom
Qt Code:
  1. bool CustomModel::appendCustom(Custom *custom, const QModelIndex &parent)
  2. {
  3. beginInsertRows(parent, customs.count(), customs.count()+1);
  4. customs.append(custom);
  5. endInsertRows();
  6. return true;
  7. }
To copy to clipboard, switch view to plain text mode 
MainWindow
Qt Code:
  1. MainWindow::MainWindow(QWidget *parent) :
  2. QMainWindow(parent),
  3. ui(new Ui::MainWindow)
  4. {
  5. ui->setupUi(this);
  6.  
  7. model = new CustomModel(this);
  8. ui->tableView->setModel(model);
  9.  
  10. connect(ui->actionAddItem, &QAction::triggered, this, &MainWindow::onAddCustom);
  11. }
To copy to clipboard, switch view to plain text mode 
onAddCustom
Qt Code:
  1. void MainWindow::onAddCustom()
  2. {
  3. Custom* new_custom = new Custom();
  4.  
  5. model->appendCustom(new_custom);
  6. }
To copy to clipboard, switch view to plain text mode