QTreeWidget 给树控件添加响应事件 的案例
import sys
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import QApplication, QWidget, QTableWidget, QTableWidgetItem, QMenu, QVBoxLayout, QMainWindow, \
QTreeWidget, QTreeWidgetItem
'''
QTreeWidget 给树控件添加响应事件 的案例
'''
class TreeEventDemo(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
# 设置定位和左上角坐标
self.setGeometry(300, 300, 460, 360)
# 设置窗口标题
self.setWindowTitle('QTreeWidget 给树控件添加响应事件 的演示')
# 设置窗口图标
# self.setWindowIcon(QIcon('../web.ico'))
self.tree = QTreeWidget()
# 为树控件指定列数
self.tree.setColumnCount(2)
# 指定列标签
self.tree.setHeaderLabels(["Key", "Value"])
root = QTreeWidgetItem(self.tree)
root.setText(0, '根节点')
root.setIcon(0, QIcon('../web.ico'))
# self.tree.setColumnWidth(0, 160)
# 添加子节点
child1 = QTreeWidgetItem(root)
child1.setText(0, '子节点1')
child1.setText(1, '1')
# child1.setIcon(0, QIcon('../web.ico'))
# child1.setCheckState(0, Qt.Checked)
# 添加子节点2
child2 = QTreeWidgetItem(root)
child2.setText(0, '子节点2')
child2.setText(1, '2')
child2.setIcon(0, QIcon('../web.ico'))
# 为child2添加一个子节点
child3 = QTreeWidgetItem(child2)
child3.setText(0, '子节点3')
child3.setText(1, '3')
# child3.setIcon(0, QIcon('../web.ico'))
# 展开所有节点
self.tree.expandAll()
self.tree.clicked.connect(self.onTreeClicked)
self.setCentralWidget(self.tree)
def onTreeClicked(self,index):
item = self.tree.currentItem()
print(index.row())
print('key=%s,value=%s' %(item.text(0),item.text(1)))
return
if __name__ == '__main__':
app = QApplication(sys.argv)
# 设置应用图标
app.setWindowIcon(QIcon('../web.ico'))
w = TreeEventDemo()
w.show()
sys.exit(app.exec_())