Cannot click on check box in QTreeWidget when QComboBox is added
-
Hi,
setItemWidget will put the widget in the cell over the model data and the item. You should have set autoFileBackground on cmb to true to avoid that visual situation.
-
Setting the autoFillBackground property to true does change the visual representation, but it does not solve my problem. I still cannot check or uncheck the checkbox.
Here is the code I've been working on. Maybe I'm doing something else wrong...QTreeWidget* treeWidget = ui->treeWidget; QTreeWidgetItem* myItem = new QTreeWidgetItem(treeWidget, QStringList("MyItem")); // create a regular subitem with checkbox only QTreeWidgetItem* subItem = new QTreeWidgetItem(myItem, QStringList("SubItem")); subItem->setFlags(subItem->flags() | Qt::ItemIsUserCheckable); subItem->setCheckState(0, Qt::Checked); myItem->addChild(subItem); // create the combo box QComboBox* combo = new QComboBox(treeWidget); combo->addItem("Option 1"); combo->addItem("Option 2"); combo->setAutoFillBackground(true); // this one does not have any effect // add another subitem which will have checkbox AND combo box QTreeWidgetItem* subItem2 = new QTreeWidgetItem(myItem, QStringList("")); subItem2->setFlags(subItem2->flags() | Qt::ItemIsUserCheckable); subItem2->setCheckState(0, Qt::Checked); treeWidget->setItemWidget(subItem2, 0, combo); myItem->addChild(subItem2); treeWidget->addTopLevelItem(myItem);
-
The point of setItemWidget is that you "overwrite" content of the cell i.e. you want the widget to show in place of the content of the widget. If you want to have both a check box and a combo box you should consider writing a QStyledItemDelegate.
-
According to the Qt document(setItemWidget):
"This function should only be used to display static content in the place of a tree widget item. If you want to display custom dynamic content or implement a custom editor widget, use QTreeView and subclass QItemDelegate instead."
Also, read the following article.
Can't change state of checkable QListViewItem with custom widget
-
@fantaz Welcome!
I have a little tricky solution:
connect(ui->treeWidget, &QTreeWidget::itemClicked, [&](QTreeWidgetItem *item, int column){ if (ui->treeWidget->itemWidget(item, column)) item->setCheckState(column, (item->checkState(column) == Qt::Checked) ? Qt::Unchecked : Qt::Checked); });
I hope that you see.