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?

    Thanks.



  • Hi,

    I guess you should use "removeRow":http://doc.qt.nokia.com/4.7/qtablewidget.html#removeRow

    Tony.



  • 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[items.at(i).row()] = -1; //garbage value
    }
    QList<int> rowsList = rowsMap.uniqueKeys();
    qSort(rowsList);

    //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--){
    table.removeRow(rowList.at(i));
    }@



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

    By using this form of removeRow

    ui->tablewidget->removeRow(ui->tablewidget->currentRow());

    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);

    while(selectionRangeListIter.hasNext()){
        rowIndex = ((int)((QTableWidgetItem*)selectionRangeListIter.next())->row());
        this->ui->MS2SpectrumInputTableWidget->removeRow(rowIndex);
    }
    //this->update();
    

    }@

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

    Manoj


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.