Configuring checkbox when using QTreeWidget
-
Hello, I was trying to make something like this using PyQt 5.11.2 and Qt Designer.
So I marked the "UserCheckable" flag to expect a checkbox next to items "XXX", "YYY", and "ZZZ".
However, the checkboxes don't appear.
Is it not possible to configure the items to have checkboxes with Qt Designer?
Do I have to type the code "ItemIsUserCheckable" manually?-Regards
-
Hi,
After a quick test, it seems to you have to use
setCheckState(Qt::Unchecked)
orsetCheckState(Qt::Checked)
if you want to have the checkbox appearing in your GUI. -
@MATTK said in Configuring checkbox when using QTreeWidget:
is this a bug or a known issue from Qt Designer?
No, it's 100% intended behaviour. the condition is checked here
You have 2 options:
- set the
Qt::CheckStateRole
for the indexes you want to have a checkbox. In your widget constructor you'd call something likesetUnchecked(ui->treeWidget->model());
void setUnchecked(QAbstractItemModel* model, const QModelIndex& parent = QModelIndex()){ if(!model) return; for(int i=0, maxRow=model->rowCount(parent);i<maxRow;++i){ for(int j=0, maxCol=model->columnCount(parent);j<maxCol;++j){ const QModelIndex currIdx = model->index(i,j,parent); model->setData(currIdx,Qt::Unchecked,Qt::CheckStateRole); if(model->hasChildren(currIdx)) setUnchecked(model,currIdx); } } }
- subclass the delegate to check the flag instead of
Qt::CheckStateRole
and call something likeui->treeWidget->setItemDelegate(new CheckFlagDelegate(this));
in your widget constructor
class CheckFlagDelegate : public QStyledItemDelegate{ Q_OBJECT Q_DISABLE_COPY(CheckFlagDelegate) public: explicit CheckFlagDelegate(QObject* parent = Q_NULLPTR) : QStyledItemDelegate(parent){} protected: void initStyleOption(QStyleOptionViewItem *option, const QModelIndex &index) const Q_DECL_OVERRIDE{ QStyledItemDelegate::initStyleOption(option,index); if(index.model()->flags(index) & Qt::ItemIsUserCheckable) option->features |= QStyleOptionViewItem::HasCheckIndicator; } };
Since the functionality is defined in a QObject (the delegate) and not in a QWidget this is not something designer can and probably ever will manage
- set the