Nominate our 2022 Qt Champions!

QTableView row remove

  • hi
    I created a table view like this :

    I have a create button to create new rows and as you can see I defined a button for each row to delete that row by this code :

    @int i = 0;
    QPushButton *viewButton;
    QStandardItemModel *model;
    void MainWindow::on_pushButton_clicked()
    model->appendRow(new QStandardItem(QString("")));
    viewButton = new QPushButton();
    viewButton->setText("Delete " + QString::number(i));
    ui->tableView->setIndexWidget(model->index(i , 7), viewButton);
    connect(viewButton , SIGNAL(clicked()) , this , SLOT(button_clicked()));

    and I created a slot for each button clicked for remove a row :

    @void MainWindow::button_clicked()
    // by this line I can get the sender of signal
    QPushButton *pb = qobject_cast<QPushButton *>(QObject::sender());

    as you can see I know witch button sends signal and now I need to delete that row.
    here is my question :
    how can I get the row of sender button in table view to remove that row?
    I searched everywere and I didn't realise how to get the row and column of an item.

    thanks in advices

  • Problem is that you have a widget (not an item) which knows nothing about table.
    If I needed to delete rows I usually delete selected rows and never added buttons to table itself. Selection is easy to obtain.

    If you insist on your design you may check if
    currentChanged ( const QModelIndex & current, const QModelIndex & previous )
    is emitted when you click your push button.
    If yes the current index will tell you row to delete - just remember it and use in
    your button_clicked slot.

    If not the only way I see is to iterate over each row in button_clicked and compare pb pointer with of the widget at that specific row.
    It is not at least efficient.

    Hope this helps.

Log in to reply