QtreeView通过haderdata获取父节点并显示
时间: 2024-05-22 08:12:05 浏览: 143
QTreeView通过设置headerData方法来获取父节点并显示,具体步骤如下:
1. 在数据模型中添加一个父节点列(或者一个父节点指针),并在headerData方法中返回父节点名称或者指针。
2. 在QTreeView中设置headerData方法,将父节点列或指针与treeview的父节点关联起来,使其可以被正确显示。
示例代码如下:
```python
class MyModel(QAbstractItemModel):
def __init__(self, parent=None):
super(MyModel, self).__init__(parent)
self._data = [
['Parent1', 'Child1', 'Child2'],
['Parent2', 'Child3', 'Child4'],
['Parent3', 'Child5', 'Child6', 'SubChild1'],
['Parent4', 'Child7', 'Child8', 'SubChild2'],
]
self._parent_col = 0 # 父节点所在列
def headerData(self, section, orientation, role=Qt.DisplayRole):
if role == Qt.DisplayRole:
if orientation == Qt.Horizontal:
if section == self._parent_col:
return 'Parent'
else:
return 'Child'
# 其他方法省略
class MyTreeView(QTreeView):
def __init__(self, parent=None):
super(MyTreeView, self).__init__(parent)
self.setModel(MyModel(self))
def headerData(self, section, orientation, role=Qt.DisplayRole):
if role == Qt.DisplayRole:
if orientation == Qt.Horizontal:
if section == self.model()._parent_col:
return self.model().headerData(section, orientation, role)
else:
return super().headerData(section, orientation, role)
if __name__ == '__main__':
app = QApplication(sys.argv)
view = MyTreeView()
view.show()
sys.exit(app.exec_())
```
在上面的示例代码中,MyModel类中新增了一个父节点列(即第0列),并在headerData方法中返回该列的名称为'Parent'。在MyTreeView类中重新实现了headerData方法,当section为父节点列时,返回MyModel中headerData方法得到的父节点名称;否则调用父类的headerData方法。最终的效果如下图所示:

阅读全文
相关推荐

















