Get inherited QTreeWidgetItem
-
Hi!
I inherited in QTreeWidgetItem and set this item to QTreeWidget. How I can get MyTreeWidgetItem from QTreeWidget in signal currentItemChanged and function currentItem()?class MyTreeWidgetItem : public QObject, public QTreeWidgetItem { Q_OBJECT public: MyTreeWidgetItem(){}; int id = -1; int type = TypeItemProtocol::protocol; QVector <int> vector; void setId(int value){id = value;} int getId(){return id;} void setType(int typeValue) {type = typeValue;} int getType() {return type;} void addInVector(int value) {vector.append(value);} }; -
Hi!
I inherited in QTreeWidgetItem and set this item to QTreeWidget. How I can get MyTreeWidgetItem from QTreeWidget in signal currentItemChanged and function currentItem()?class MyTreeWidgetItem : public QObject, public QTreeWidgetItem { Q_OBJECT public: MyTreeWidgetItem(){}; int id = -1; int type = TypeItemProtocol::protocol; QVector <int> vector; void setId(int value){id = value;} int getId(){return id;} void setType(int typeValue) {type = typeValue;} int getType() {return type;} void addInVector(int value) {vector.append(value);} }; -
It is work
void MainWindow::on_treeWidgetSession_currentItemChanged(QTreeWidgetItem *current, QTreeWidgetItem *previous) { MyTreeWidgetItem* item = static_cast<MyTreeWidgetItem*>(current); -
@Mihaill You should always check pointers after casts! If cast fails because the object is not MyTreeWidgetItem you will get nullptr and your app will crash if you try to use it.
@jsulm said in Get inherited QTreeWidgetItem:
You should always check pointers after casts!
... and use the correct cast - static_cast<> is very problematic here since you can't huarantee that every item is a MyTreeWidgetItem here. Use dynamic_cast<> or qobject_cast<>
-
@Mihaill You should always check pointers after casts! If cast fails because the object is not MyTreeWidgetItem you will get nullptr and your app will crash if you try to use it.
@jsulm said in Get inherited QTreeWidgetItem:
If cast fails because the object is not MyTreeWidgetItem you will get nullptr
True for
dynamic_cast<>. The only time OP'sstatic_cast<>would returnnullptris ifQTreeWidgetItem *current == nullptr, not if it were say plainQTreeWidgetItem *. Just saying..... -
@jsulm said in Get inherited QTreeWidgetItem:
You should always check pointers after casts!
... and use the correct cast - static_cast<> is very problematic here since you can't huarantee that every item is a MyTreeWidgetItem here. Use dynamic_cast<> or qobject_cast<>
@Christian-Ehrlicher said in Get inherited QTreeWidgetItem:
or qobject_cast<>
=>
qobject_cast<MyTreeWidgetItem*>(current);Here
MyTreeWidgetItemisQObjectbutcurrent's formal type isQTreeWidgetItem, which is notQObject. In this situation isqobject_cast<>allowed?