效果图
完整代码
import sys
from PyQt5.QtWidgets import QTreeWidget,QTreeWidgetItem,QHBoxLayout,QWidget,QApplication,QMainWindow
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import Qt
class QListWidgetDemo(QMainWindow):
def __init__(self):
super(QListWidgetDemo, self).__init__()
self.resize(400, 150)
self.setWindowTitle("QListWidgetDemo")
self.tree = QTreeWidget()
self.tree.setColumnCount(2)
self.tree.setHeaderLabels(['Key','Value'])
root = QTreeWidgetItem(self.tree)
root.setText(0,'Root')
root.setIcon(0,QIcon('./u1.ico'))
self.tree.setColumnWidth(0,150)
child1 = QTreeWidgetItem()
child1.setText(0,'child1')
child1.setText(1,'ios')
child1.setIcon(0,QIcon('./u2.ico'))
root.addChild(child1)
child2 = QTreeWidgetItem(root)
child2.setText(0,'child2')
child2.setText(1,'')
child2.setIcon(0,QIcon('./u3.ico'))
child3 = QTreeWidgetItem(child2)
child3.setText(0,'child3')
child3.setText(1,'android')
child3.setIcon(0,QIcon('./images/music.png'))
self.tree.addTopLevelItem(root)
self.tree.clicked.connect(self.onClicked)
self.tree.expandAll()
layout = QHBoxLayout()
layout.addWidget(self.tree)
mainFrame = QWidget()
mainFrame.setLayout(layout)
self.setCentralWidget(mainFrame)
def onClicked(self, item):
item = self.tree.currentItem()
print('Key=%s,value=%s'%(item.text(0),item.text(1)))
if __name__ == '__main__':
app = QApplication(sys.argv)
main = QListWidgetDemo()
main.show()
sys.exit(app.exec_())