11

I'm trying to enter edit mode on a specific cell like this:

void MainWindow::on_addButton_released() {
    tm->addRow();
    tableView->scrollToBottom();
    int ec=tm->firstWritableColumn();
    int r=tm->rowCount(QModelIndex());
    QModelIndex id = tm->index(r, ec, QModelIndex());
    tableView->setCurrentIndex(id);
    tableView->edit(id);
    qDebug() << "row:" << r << " col:" << ec << "index:" << id;
}

My model creates an index like this:

QModelIndex TableModel::index(int row,int column,QModelIndex parent) const {
    Q_UNUSED(parent);
    return createIndex(row,column,0);
}

The debug output looks like this:

row: 9  col: 1 index: QModelIndex(9,1,0x0,TableModel(0xbf3f50) )  

I'm fairly sure that the index is somehow invalid as setCurrentIndex() doesn't seem to be working.

Marc Mutz - mmutz
  • 24,485
  • 12
  • 80
  • 90
Chris Camacho
  • 1,164
  • 1
  • 9
  • 31

1 Answers1

15

OMG! ground swallow me up!

row numbers start with row 0, I needed to do

int r=tm->rowCount(QModelIndex())-1;
QModelIndex id=tm->index(r,ec,QModelIndex());
Chris Camacho
  • 1,164
  • 1
  • 9
  • 31
  • 3
    I forget this constantly with widget toolkits, so I try never to use `row` or `column` alone. Instead, I use `rowIndex` (for zero-based) and, much more rarely, `rowNumber` (for one-based). – kevinarpe May 12 '15 at 04:50
  • 'tm' must be the table model over here?? – oya163 Jul 04 '16 at 11:00