Some colleagues asked this question. After debugging, it is found that the getparent method is not implemented in the contentprovider of treeviewer. The getparent method is described as follows:
public Object getParent(Object element)
The tree viewer callits content provider's getparent method when it needs to reveal collapsed domain objects programmatically and to set the expanded state of domain objects. this method shoshould answer the parent of the domain object element.
In the eclipse FAQ, we also see the following arguments: How do I programmatically select an item in the tree?
Call the tree viewer's setselection (New structuredselection (<domain model>), true ).
The premise is that you need to implement the getparent method of the tree's contentprovider. Because you need to select a deep node, you must search for the node from the root (find the child through the parent, note that the parent here refers to the tree or treeitem) therefore, getparent must be correctly implemented.
In addition, the model equals method also needs to be correctly implemented (internally implemented through equlas ). Another question is, does the domain model we pass in retrieve from the tree traversal or a new anonymous object? Paste the chat record directly: Wang xuechuan 16:43:11
What is the best solution for the parameter model? Do you need a new one?
Passengers 16:43:16
Internal processing is performed through equals.
Can you get the instance of the model you want to select?
Yes, just transfer it
Wang xueshuan 16:43:43
Yes
This object needs to be retrieved from the root Model
Comparison
Right
Passengers 16:44:17
No, you have to build it on your own, but it is obviously not suitable for complicated or large equlas objects.
Wang xueshuan 16:45:07
Oh, new is more efficient.
Otherwise, traverse from root until the selected model is found.
Passengers 16:45:34
The new object is also a temporary obsolete object.
Wang xueshuan 16:45:51
It can only be traversed.
Passengers 16:46:12
This method can also be used for small objects. For example, if your object's equlas only pays attention to one or two attributes, such as the node name, you can also create a new
Wang xueshuan 16:46:44
Yes. Pay attention to the file path.
One
Passengers 16:47:03
That's new.
Wang xueshuan 16:47:21
Good
Passengers 16:47:23
In this way, the code is relatively simple
Passengers 16:49:35
In fact, in a dynamic tree, it is not good to traverse the tree. If your tree changes with the addition and deletion of your tree, imagine that you can still use getchildren (). get (INDEX) to obtain the number of changes, index is naturally changed (of course, you can avoid this problem by traversing and equals) with simple properties, you can locate the unique domail model and create a domail model using new.