@shobhitmittal said in Remove CellWidget from QTableWidget when focus out:
As far as I understand, if I need to show a comboBox in a tableWidget cell, I need to use setCellWidget
No, you do not need to do this (via setCellWidget()).
Search the QTableWidget docs page, and that of QTableView from which it inherits, for edit. Qt has the "framework" for going in & out of edit mode on a cell without you having to to ever call setCellWidget. I believe that by doing that you will find that if the user clicks away from the combobox editor (which appears when editing starts) the framework will get rid of that comboxbox for you.
Actually the editor facilities are shown under QAbstractItemView Class, from which QTreeView (and therefore QTableWidget too) inherits. You will use code including
tableWidget->setEditTriggers(QAbstractItemView::AllEditTriggers); item->setFlags(item->flags() | Qt::ItemIsEditable);Those lines make an item editable by double-clicking (I think) on a cell.
Ultimately you should use void QAbstractItemView::setItemDelegate(QAbstractItemDelegate *delegate). You should subclass your own QAbstractItemDelegate. Override its QWidget *QAbstractItemDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const. Have that return a new QComboBox for your case. Then the Qt infrastructure will be responsible for showing and destroying the combobox for you.
Qt's Star Delegate Example provides editablity and shows what you need to do. There may be other examples. Ultimately you will be creating a QStyledItemDelegate and overriding its "editor" methods to return a combobox to use and populating that combo's items.