pyqt5给treewidget获取点击项的序号
时间: 2023-07-15 12:13:47 浏览: 84
可以通过`currentItem()`方法获取当前被选中(点击)的项,然后再通过`indexOfTopLevelItem()`或者`indexOfChild()`方法获取该项在顶级项或子项中的序号。下面是一个示例代码:
```python
from PyQt5.QtWidgets import QApplication, QTreeWidget, QTreeWidgetItem
import sys
class TreeWidget(QTreeWidget):
def __init__(self, parent=None):
super().__init__(parent)
# 添加顶级项
top_items = [QTreeWidgetItem(['Item {}'.format(i)]) for i in range(1, 6)]
self.addTopLevelItems(top_items)
# 添加子项
for i in range(5):
child_items = [QTreeWidgetItem(['Item {}.{}'.format(i+1, j+1)]) for j in range(3)]
top_items[i].addChildren(child_items)
# 设置信号槽
self.itemClicked.connect(self.on_item_clicked)
def on_item_clicked(self, item, column):
# 获取当前点击项在顶级项或子项中的序号
if item.parent() is None:
index = self.indexOfTopLevelItem(item)
print('Clicked top item {}: {}'.format(index, item.text(column)))
else:
parent = item.parent()
index = parent.indexOfChild(item)
top_index = self.indexOfTopLevelItem(parent)
print('Clicked child item {}.{}: {}'.format(top_index, index, item.text(column)))
if __name__ == '__main__':
app = QApplication(sys.argv)
treeWidget = TreeWidget()
treeWidget.show()
sys.exit(app.exec_())
```
当点击某个项时,会在控制台输出该项在顶级项或子项中的序号和文本内容。例如,当点击顶级项`Item 3`时,会输出:
```
Clicked top item 2: Item 3
```
当点击该项下的子项`Item 3.2`时,会输出:
```
Clicked child item 2.2: Item 3.2
```
阅读全文