QTreeViewのルートノードを取得するにはどうすればいいですか?

QTreeViewでは、model()メソッドでツリービューで使用しているモデルを取得します。そして、モデルのindex()メソッドでルートノードのインデックスを取得し、モデルのparent()メソッドでそのノードの親ノードのインデックスを取得し、親ノードがないルートノードを取得するまで繰り返します。

サンプルコードは以下のようになります。

root_index = treeview.model().index(0, 0)  # 获取第一个节点的index
while treeview.model().parent(root_index).isValid():
    root_index = treeview.model().parent(root_index)  # 获取父节点的index
root_node = root_index.internalPointer()  # 获取根节点

なお、上記のサンプルコードでは、(0, 0)はルートノードの位置を表しており、実際の状況に合わせて位置調整を行ってください。

bannerAds