Important: Please read the Qt Code of Conduct -

QTableWidget - how to delete a row?

  • What is the best way to delete a row in a QTableWidget table?
    I'm probably missing something, but all I can see so far is "delete", and that only deletes the contents of a single cell (row,col).

    I want to implement code to find and remove a table row, shifting all the remaining rows up to close the gap.

    I can use findItems to find the relevant cell, but this just returns a QTableWidgetItem, not the row/col.

    Do I need to implement a loop, looking at each row in turn, in order to find the row to be deleted, or is there a better way?


  • Hi,

    I guess you should use "removeRow":


  • Thanks Tony.

    I thought there might be a way to avoid the loop, not that it's difficult.
    I was hoping there might be a way of identifying the row to be deleted using the "findItems" utility, rather than having to interrogate each row in turn.

    Anyway, I'll stick with the loop, thanks for your help.

  • bq. I can use findItems to find the relevant cell, but this just returns a QTableWidgetItem, not the row/col.

    You can still use findItems.
    findItems would return QList<QTableWidgetItem *>. You can do following:

    @QList<QTableWidgetItem*> items = table.findItems(.....);
    QMap<int, int> rowsMap;
    for(int i = 0; i < items.count(); i++{
    rowsMap[] = -1; //garbage value
    QList<int> rowsList = rowsMap.uniqueKeys();

    //Now go through your table and delete rows in descending order as content would shift up and hence cannot do it in ascending order with ease.
    for(int i = rowList.count() - 1; i >= 0; i--){

  • I believe that by using the "removeRow" function you can do your job vrey easy.

    By using this form of removeRow


    you can remove the row you have selected and shift ,the cells above this row, up.

  • Hi All,
    You can try below code

    void MSSPectumInputDockWidget::handleDeleteSelectedRow()
    QList<QTableWidgetItem*> selectionRangeList = this->ui->MS2SpectrumInputTableWidget->selectedItems();
    int rowIndex;
    QListIterator<QTableWidgetItem*> selectionRangeListIter(selectionRangeList);

        rowIndex = ((int)((QTableWidgetItem*)>row());


    Still under testing :) for different test cases . Enjoy coding......


Log in to reply