pyqt5给treewidget获取点击项的序号
时间: 2023-12-03 10:42:27 浏览: 90
可以使用QTreeWidget的`currentItemChanged`信号来获取点击项的序号。
示例代码:
```python
from PyQt5.QtWidgets import QApplication, QTreeWidget, QTreeWidgetItem
from PyQt5.QtCore import Qt
app = QApplication([])
tree = QTreeWidget()
tree.setColumnCount(1)
tree.setHeaderLabels(['Name'])
for i in range(5):
item = QTreeWidgetItem(tree, ['Item {}'.format(i)])
for j in range(3):
child = QTreeWidgetItem(item, ['Child {}'.format(j)])
def on_item_clicked(item):
if item is not None:
index = tree.indexFromItem(item).row()
print('Clicked item index:', index)
tree.currentItemChanged.connect(on_item_clicked)
tree.show()
app.exec_()
```
在这个例子中,我们创建了一个包含多个父节点和子节点的QTreeWidget。然后连接`currentItemChanged`信号到`on_item_clicked`槽函数。当用户点击树中的项时,槽函数会被调用,并在控制台输出点击项的序号。注意,序号从0开始计数。
阅读全文