How to add extra data to a tree item?

356 Views Asked by At

I'm trying to add extra data to a wx Tree Item using wxTreeItemData, but I cannot construct a wxTreeItemData object, because the constructor doesn't have any parameters.

Here is my sample code:

wxTreeCtrl treeCtrl = new wxTreeCtrl(parentWindow);
treeCtrl->AddRoot("Root");
treeCtrl->AppendItem(root, "item", -1,-1, "some extra data");
/** Signature help for inline ​​​wxTreeItemId​ ​‌​​AppendItem​(const ​​​wxTreeItemId​ &​​‌parent​, const ​​​wxString​ &​​‌text​, int ​​‌image​ = -1, int ​​‌selImage​ = -1, ​​​wxTreeItemData​ *​​‌data​ = (​​​wxTreeItemData​ *)0). Summary: insert a new item in as the last child of the parent. Current parameter 3 of 5: , . **/

This gives me an error:

E0413. no suitable conversion function from "std::string" to "wxTreeItemData *" exists  

But when I pass a wxTreeItemData object nothing happens, because the object is empty.

The wxTreeItemData constructor is without any parameters!

Does anyone know how to add data to a wxTreeItemData object?

Another try

I declared a new class that is derived from the `wxTreeItemData` class, then added a string that will hold the data, and then, I declared, and defined a method to return the data. Code sample:
wxTreeItemId item = treeCtrl->AppendItem(Root, "item", -1,-1, new DataItem("some extra data"));
// It should set the new DataItem object as a wxTreeItemData
// I'll try to get the data object from the TreeCtrl:
DataItem *data = treeCtrl->GetItemData(item);
// Signature help for virtual ​​​wxTreeItemData​ * ​‌​​GetItemData​(const ​​​wxTreeItemId​ &​​‌item​) const.
// Trying to print the data:
std::cout << data->GetData();
// It should print the data.

Error:

E0144. a value of type "wxTreeItemData *" cannot be used to initialize an entity of type "DataItem *"

Because the method GetItemData() returns a wxTreeItemData object. And if I tried to replace the DataItem to wxTreeItemData, I cannot invoke the GetData() method of my DataItem object.

Helpful resources:

[wxWidgets: wxTreeCtrl Class Reference][1]

wxWidgets: wxTreeItemData Class Reference

1

There are 1 best solutions below

4
VZ. On BEST ANSWER

You indeed need to derive your class from wxTreeItemData, as you've done, and you need to cast the returned value of GetItemData() to the correct value, i.e. write

DataItem *data = static_cast<DataItem*>(treeCtrl->GetItemData(item));

This is safe as long as you only pass actual DataItem objects (and not something else) to SetItemData().