I have a QTreeWidgetItem that I want to disable under certain circumstances to prevent users from using incompatible options. I'm working with Qt 5.15.2.
QTreeWidgetItem has a function, QTreeWidgetItem::setDisabled(bool disabled), but sadly this only seems to grey it out - it does not prevent a user from clicking the arrow and expanding or un-expanding the tree item.
There is of course QTreeWidgetItem::setExpanded(bool expand), but that only sets it once - it doesn't prevent the user from expanding.
Is there some way to completely disable the tree item, so a user cannot open it? I tried QTreeWidgetItem::setFlags(Qt::ItemFlags flags) with flags set to 0, so every option should be disabled, but this did not make any difference.
The only remaining way is to disable each of the children, but the only trouble is that those children have other cases where they need to be disabled and enabled, so simply re-enabling them all would be wrong - some of those children would still need to be off. I suppose you could store the previous state of all the children, but that's cumbersome and prone to error.

One possibility is to set the
Qt::ItemNeverHasChildrenflag for the parent item, along with the current ones.Note that that flag is intended for optimization purposes only, but it should be fine to use it within a QTreeWidget.
Just ensure that the item is not expanded, set the flag along with the existing flags, and ensure that you update the viewport.
I can't really write in C++, so I wouldn't risk posting bad code, but this is how I would do it in PyQt/PySide, which should be quite self explanatory:
You could even implement it in a custom QTreeWidgetItem subclass, and always use that as a prototype for the tree widget.
Be aware that, if the item is already part of the view,
setExpanded(False)will obviously trigger thecollapsedanditemCollapsedsignals, possibly causing some level of recursion in a custom implementation that uses those signals.