Nominate our 2022 Qt Champions!

QTableWidget + setCellWidget(myWidget) how remove from Cell without delete myWidget ?

  • Hi!
    I insert single myWidget to QTableWidget by setCellWidget().
    When I using removeCellWidget() function myWidget is removed for ever, but it still will be necessary to me repeatedly.
    How correctly remove from Cell myWidget without delete myWidget?

  • it hardly, takeItem works with QTableWidgetItem, but not with QWidget. Different mechanisms.

  • Moderators

    There is no way - currently.
    The index widget will be deleted whenever a new index widget is set.
    removeCellWidget() simply sets a NULL-widget. So you have implicitly the same problem.

    What exactly is your usecase?

    An alternative would be to add a container widget. for example: QStackedWidget
    And add the widgets there, so Qt doesn't delete them.

    if( QStackedWidget* w = qobject_cast<QStackedWidget*>( tableWidget->cellWidget(r,c) )
         w->addWidget( ... )  // set widget
         w->removeWidget( ... );  //remove widget
         w->setCurrentIndex( ... ) / w->setCurrentWidget( ... );  //switch widgets

  • Thanks. But unfortunately I have other usecase, I shouldn't replace widgets in a cell, I should return to a cell initial properties which were to setCellWidget.

    void MainWindow::on_tableWidget_cellEntered(int row, int column)
    QStackedWidget *sw=new QStackedWidget;
    int r=cellwidgetcoord.row; 
    int c=cellwidgetcoord.column;
    ui->tableWidget->setCellWidget(row, column, sw);

  • Moderators

    maybe it's enough to simply hide it

Log in to reply