View Full Version : QTreeWidgetItem does not inherit QObject

19th January 2010, 23:39
Curiously, QTreeWidgetItem does not inherit QObject. Because of that, a subclass pointer cannot be retrieved with qobject_cast, but the normal C++ dynamic_cast must be used. Is there a reason for this omission? (I'm using a subclass to store a viewable widget for another view.) It's no great problem, but just seems odd.

20th January 2010, 02:36
QObject is a tool, not a panaceum. Not every class has to be derived from QObject.

To quote the docs:

When subclassing QTreeWidgetItem to provide custom items, it is possible to define new types for them so that they can be distinguished from standard items. The constructors for subclasses that require this feature need to call the base class constructor with a new type value equal to or greater than UserType.

In other words:

class MyItem : public QTreeWidgetItem {
enum { Type = QTreeWidgetItem::UserType+1 };
MyItem() : QTreeWidgetItem(Type){}

QTreeWidgetItem *item = new MyItem;
if(item->type()==MyItem::Type) {
MyItem *myItem = static_cast<MyItem*>(item);

20th January 2010, 16:35
Thanks, I saw the possibility. I got caught trying to use a slot into the item to change an internal pointer, the "displayable", but I found another way to accomplish the task. I was just indulging in my curiosity with this post. I was probably overusing signals and slots, but I find that abstraction so convenient.