0

When I use Qt tableView, I can just set item in the first row. When I click add, it will cover the former, but not set a new item. Maybe my slot function is incorrect. But I don't know how to handle it.

void Widget::on_addButton_clicked()
{   int i = 0;
    EditDialog editDialog(this);
    if(editDialog.exec() == 1)
    {
        model->setItem(i,0,new QStandardItem(editDialog.getID()));
        model->setItem(i,1,new QStandardItem(editDialog.getPriority()));
        model->setItem(i,2,new QStandardItem(editDialog.getTime()));
    }
    i++;
}
Felix
  • 6,217
  • 1
  • 26
  • 50
F.H.
  • 39
  • 5
  • 1
    I once wrote an answer to [SO: Stop QTableView from scrolling as data is added above current position](https://stackoverflow.com/a/42460216/7478597) which I tested with prepend as well as append. Btw. _Maybe my slot funcition is incorrect!!_ This is hard to judge without a [mcve]. – Scheff's Cat Nov 03 '18 at 17:23
  • Sorry , this is my first time to visite Stackflow ,I'm not familiar with it @Scheff – F.H. Nov 03 '18 at 17:55
  • Btw. the `i++;` is somehow useless in the exposed code. `i` is a local variable. So, it will be initialized with `0` on each call of `Widget::on_addButton_clicked()` (and get lost when leaving the function). – Scheff's Cat Nov 03 '18 at 18:12

1 Answers1

1

Please, have a look into doc. QStandardItemModel::setItem():

Sets the item for the given row and column to item. The model takes ownership of the item. If necessary, the row count and column count are increased to fit the item. The previous item at the given location (if there was one) is deleted.

(Emphasizing is mine.)

If a row shall be inserted before end of table (e.g. as first), then it's necessary to do this explicitly.

This can be achieved by calling QStandardItemModel::insertRow() before setting the items.

This could e.g. look like this:

// fills a table model with sample data
void populate(QStandardItemModel &tblModel, bool prepend)
{
  int row = tblModel.rowCount();
  if (prepend) tblModel.insertRow(0);
  for (int col = 0; col < NCols; ++col) {
    QStandardItem *pItem = new QStandardItem(QString("row %0, col %1").arg(row).arg(col));
    tblModel.setItem(prepend ? 0 : row, col, pItem);
  }
}

I took this from an older post of mine. The complete sample can be found in my answer to SO: Stop QTableView from scrolling as data is added above current position.

Scheff's Cat
  • 16,517
  • 5
  • 25
  • 45