Class TreeModel
Represents a hierarchical model with parent-child relationships.
public abstract class TreeModel : Model
- Inheritance
-
TreeModel
- Derived
- Inherited Members
Remarks
Derive from TreeModel when a tree requires custom index identity, multiple columns, or custom role lookup. For the usual single-column, node-based case, prefer TreeModel<T>. Use NodeTreeModel<T> to adapt an existing application tree whose nodes cannot inherit TreeNode<T>.
important
A non-generic tree model cannot safely provide implementations of Index(int, int, ModelIndex), Parent(ModelIndex), or Sibling(int, int, ModelIndex). Those methods must convert a Qt.DotNet.ModelIndex.Id back to the application's node and find that node's current parent and row. The required identity and navigation rules belong to the application's tree, so subclasses must supply them.
The following outline shows the essential members of a two-column tree. The
application supplies FindNode, which resolves the stable id stored in
each Qt.DotNet.ModelIndex back to its node.
public sealed class FileTree : TreeModel
{
private readonly List<FileNode> roots = [];
public override int RowCount(ModelIndex parent) => GetChildren(parent).Count;
public override int ColumnCount(ModelIndex parent) => 2;
public override ModelIndex Index(int row, int column, ModelIndex parent)
{
var children = GetChildren(parent);
if (row < 0 || row >= children.Count || column is < 0 or >= 2)
return ModelIndex.Empty;
var node = children[row];
return new ModelIndex(row, column, node.Id);
}
public override ModelIndex Parent(ModelIndex index)
{
var parent = index is { IsValid: true } ? FindNode(index.Id)?.Parent : null;
return parent is null
? ModelIndex.Empty
: new ModelIndex(RowOf(parent), 0, parent.Id);
}
public override object Data(ModelIndex index, int role)
{
if (role != Roles.DisplayRole || index is not { IsValid: true }
|| FindNode(index.Id) is not { } node)
return null;
return index.Column == 0 ? node.Name : node.Size;
}
private IReadOnlyList<FileNode> GetChildren(ModelIndex parent) => parent switch
{
{ IsValid: false } => roots,
{ Id: var id } when FindNode(id) is { } node => node.Children,
_ => []
};
}