获取 QTreeWidgetItem 的最顶级项目

Get the most top-level item of a QTreeWidgetItem

我想找到一个 QTreeWidgetItem 的最顶层父项,无论它在树中有多深。

使用 item.parent() 的问题是如果该项目在树中有几层深,它可以 return 另一个 QTreeWidgetItem,所以我最终不得不做 item.parent().parent().parent()...etc 例如。

我没有很好地解释我的问题。但是 while 循环确实是解决方案,这将一直搜索,直到找到项目的顶级项目:

while item.parent():
    item = item.parent()