user1540939
user1540939

Reputation: 89

return a derivated QTreeWidgetItem

I think that this is not a question regarding especially Qt but a quaestion of a lack of programming expeience.

I derived a class from QTreeWidgetItem and I added some bolean flags. When i initialize a QTreeWidget I add two of them by

_NewItem1=MyQTreeWidgetItem(_treewidget);

than later I add some items by

_NewItem1_1=MyQTreeWidgetItem(_NewItem1);
_NewItem1_1->boleanvalue1=true;

If I later want to return these Items I call

(MyQTreeWidgetItem)_NewItem1->child(i)

but this of course just returns me a MyQTreeWidgetItem with newly initialized bolean flags.

Do I have to override the child function to retun the true Items which I initialized earlier?

Upvotes: 0

Views: 571

Answers (1)

divanov
divanov

Reputation: 6339

_NewItem1->child(i) returns pointer to QTreeWidgetItem, which is a base class for MyQTreeWidgetItem. You have cast is safely to MyQTreeWidgetItem, taking into account it may be also real QTreeWidgetItem. This is achieved with dynamic_cast in C++, which checks type at runtime.

QTreeWidgetItem *item = _NewItem1->child(i);
MyQTreeWidgetItem *myItem = dynamic_cast<MyQTreeWidgetItem>(item);
if (myItem) {
    qDebug() << myItem->boleanvalue1;
} else {
    qDebug() << item << "is not of type MyQTreeWidgetItem";
}

On the other hand, type-casting operator () allows to convert any type into any other type without any checking, if this kind of conversion is possible. Like, for example, you've converted pointer to QTreeWidget into object of type MyQTreeWidgetItem. The subsequent access to the variable will produce either a run-time error or a unexpected result.

Upvotes: 1

Related Questions