How to delete all rows from QTableWidget

前端 未结 10 1870
自闭症患者
自闭症患者 2021-01-31 14:57

I am trying to delete all rows from a QTableWidget . Here is what I tried.

for ( int i = 0; i < mTestTable->rowCount(); ++i )
{
    mTestTable->removeRo         


        
相关标签:
10条回答
  • 2021-01-31 15:15
    QTableWidget test;
    test.clear();
    test.setRowCount( 0);
    
    0 讨论(0)
  • 2021-01-31 15:17

    Just set the row count to 0 with:

    mTestTable->setRowCount(0);
    

    it will delete the QTableWidgetItems automatically, by calling removeRows as you can see in QTableWidget internal model code:

    void QTableModel::setRowCount(int rows)
    {
        int rc = verticalHeaderItems.count();
        if (rows < 0 || rc == rows)
            return;
        if (rc < rows)
            insertRows(qMax(rc, 0), rows - rc);
        else
            removeRows(qMax(rows, 0), rc - rows);
    }
    
    0 讨论(0)
  • 2021-01-31 15:19

    Your code does not delete last row.

    Try this one.

    int totalRow = mTestTable->rowCount();
    for ( int i = 0; i < totalRow ; ++i )
    {
           mTestTable->removeRow(i);
    }
    

    In your code, on the first time, rowCount() have value 2 and value of the i is 0, so its delete 1st row,

    But on the second time value of i incremented with 1, but rowCount() return the updated row count which is now 1, so, it does not delete the last row.

    Hope now you ll be clear.

    0 讨论(0)
  • 2021-01-31 15:24

    Removes all items not in the headers from the view. This will also remove all selections. The table dimensions stay the same.

    void QTableWidget::clearContents()
    

    Removes all items in the view. This will also remove all selections and headers.

    void QTableWidget::clear()
    
    0 讨论(0)
  • 2021-01-31 15:27

    The simple way to delete rows is to set the row count to zero. This uses removeRows() internally.

    table->setRowCount(0);
    

    You could also clear the content and then remove all rows.

    table->clearContents();
    table->model()->removeRows(0, table->rowCount());
    

    Both snippets leave the headers untouched!

    If you need to get rid of headers, too, you could switch from clearContents() to clear().

    0 讨论(0)
  • 2021-01-31 15:31

    In order to prevent an app crash, disconnect all signals from the QTableView.

    // Deselects all selected items
    ui->tableWidget->clearSelection();
    
    // Disconnect all signals from table widget ! important !
    ui->tableWidget->disconnect();
    
    // Remove all items
    ui->tableWidget->clearContents();
    
    // Set row count to 0 (remove rows)
    ui->tableWidget->setRowCount(0);
    
    0 讨论(0)
提交回复
热议问题