要获取Qt TreeView的点击事件及其内容,需要使用QTreeView的信号clicked和模型索引 QModelIndex。当用户单击Tree View中的项时,将触发clicked信号并发送包含所单击项的模型索引的参数。
以下是示例代码:
from PyQt5.QtWidgets import QTreeView, QAbstractItemView
from PyQt5.QtCore import QModelIndex
class MyTreeView(QTreeView):
def __init__(self):
super().__init__()
# 设置为单选模式
self.setSelectionMode(QAbstractItemView.SingleSelection)
# 连接clicked信号到on_clicked函数
self.clicked.connect(self.on_clicked)
def on_clicked(self, index: QModelIndex):
# 获取所选项的文本
text = index.data()
# 打印所选项的索引和文本
print(f"Index: {index.row()}, Text: {text}")
在这个例子中,我们创建了一个自定义的QTreeView类,并重写了它的构造函数。我们还将它的选择模式设置为单选模式。然后,我们连接clicked信号到on_clicked函数,以便在用户单击TreeView的项目时调用该函数。最后,在on_clicked函数中,我们使用QModelIndex的data()方法来获取所选项的文本,并打印出它的索引和文本。