Introduction to PyQt5 (fourteen) tree control QTreeWidget

table of Contents

1. Wherever your heart desires, wherever you go

2. Basic usage of the tree widget (QTreeWidget)

Three. Add response time for tree nodes

4. Add, modify and delete the nodes of the tree control

Five. QTreeView control and system customization mode


1. Wherever your heart desires, wherever you go

The night before yesterday, friend A had a treat. I happily went to the appointment. There was also a friend B of friend A. Yes, every time I see a big guy, I can’t help but feel a little bit of emotion. We are too small.

A is a student who is the same age as me, but one level older than me, but is now a PhD student at the National University of Science and Technology, and B is a graduate student of Beijing University of Posts and Telecommunications. In the dining room, I was discussing technical matters, because they were all engaged in computers. Although the directions were different, they were considered peers.

In the meantime, I also talked about life and feelings, but when I heard them talk about projects, internships, competitions, income, etc., I felt that they weren't a person of the same level. Hey, autism on the road to becoming stronger is really inevitable.

After dinner, it was past nine o'clock, so I just lived in A's house.

Although I don’t have the ability to do them, it’s not a cool thing to implement my original intention and fight for the things I love for a lifetime.

After a day of playing today, I returned home in the evening. After dinner, I wrote down this feeling, and everyone encouraged me.

 

2. Basic usage of the tree widget (QTreeWidget)

Code:

import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *


class BasicTreeWidget(QMainWindow):
    def __init__(self,parent=None):
        super(BasicTreeWidget, self).__init__(parent)
        self.setWindowTitle('树控件(QTreeWidget)的基本用法')
        self.resize(500,300)

        #树
        self.tree=QTreeWidget()
        #为树控件指定列数
        self.tree.setColumnCount(2)
        #指定列标签
        self.tree.setHeaderLabels(['Key','Value'])

        #根节点
        root=QTreeWidgetItem(self.tree)
        root.setText(0,'根节点') # 0代表第一列,即Key列
        root.setIcon(0,QIcon('../picture/bag/bag1.jpg')) #为节点设置图标
        self.tree.setColumnWidth(0,200)#第一列列宽设为200

        #添加子节点1
        child1=QTreeWidgetItem(root)
        child1.setText(0,'子节点1')#第一列Key为 子节点1
        child1.setText(1,'子节点1的数据')#第二列Value为 子节点1的数据
        child1.setIcon(0,QIcon('../picture/bag/bag2.jpg'))
        #设置子节点1开启复选框状态
        child1.setCheckState(0,Qt.Checked)

        # 添加子节点2
        child2=QTreeWidgetItem(root)
        child2.setText(0,'子节点2')
        child2.setIcon(0,QIcon('../picture/bag/bag3.jpg'))

        #为child2添加一个子节点
        child3=QTreeWidgetItem(child2)
        child3.setText(0,'子节点2-1')
        child3.setText(1,'新的值')
        child3.setIcon(0,QIcon('../picture/bag/bag4.jpg'))

        #默认所有节点都处于展开状态
        self.tree.expandAll()

        #将树控件设为中心控件,即树控件会自动铺满整个屏幕
        self.setCentralWidget(self.tree)


if __name__=='__main__':
    app=QApplication(sys.argv)
    main=BasicTreeWidget()
    main.show()
    sys.exit(app.exec_())

operation result:

 

Three. Add response time for tree nodes

Code:

import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *


class TreeEvent(QMainWindow):
    def __init__(self,parent=None):
        super(TreeEvent, self).__init__(parent)
        self.setWindowTitle('为树添加响应事件')
        self.resize(400,300)

        #树
        self.tree=QTreeWidget()
        #为树控件指定列数
        self.tree.setColumnCount(2)
        #指定列标签
        self.tree.setHeaderLabels(['Key','Value'])

        #根节点
        root=QTreeWidgetItem(self.tree)
        root.setText(0,'root') # 0代表第一列,即Key列,值为root
        root.setText(1,'0')

        #添加子节点child1
        child1=QTreeWidgetItem(root)
        child1.setText(0,'child1')
        child1.setText(1,'1')

        # 添加子节点child2
        child2=QTreeWidgetItem(root)
        child2.setText(0,'child2')
        child2.setText(1,'2')

        #为child2添加一个子节点child3
        child3=QTreeWidgetItem(child2)
        child3.setText(0,'child3')
        child3.setText(1,'3')

        #信号和槽
        self.tree.clicked.connect(self.onTreeClicked)

        #将树控件设为中心控件,即树控件会自动铺满整个屏幕
        self.setCentralWidget(self.tree)

    def onTreeClicked(self,index): #index是被点击节点的索引
        item=self.tree.currentItem()#获得当前单击项
        print('当前处于第%d行'%index.row())#输出当前行(自己父节点的第几个值)
        print('key=%s,value=%s'%(item.text(0),item.text(1)))
        print()


if __name__=='__main__':
    app=QApplication(sys.argv)
    main=TreeEvent()
    main.show()
    sys.exit(app.exec_())

operation result:

   eg: child1 is the first node of root, so the number of rows is 0; child2 is the second node of root, so the number of rows is 1; child3 is the first node of child2, so the number of rows is 0

 

4. Add, modify and delete the nodes of the tree control

Code:

import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *


class ModifyTree(QWidget):
    def __init__(self,parent=None):
        super(ModifyTree, self).__init__(parent)
        self.setWindowTitle('增加修改和删除树控件中的节点')
        self.resize(400,300)

        operatorLayout=QHBoxLayout()#水平布局

        addBtn=QPushButton('添加节点')
        updateBtn=QPushButton('修改节点')
        deleteBtn=QPushButton('删除节点')

        operatorLayout.addWidget(addBtn)
        operatorLayout.addWidget(updateBtn)
        operatorLayout.addWidget(deleteBtn)

        addBtn.clicked.connect(self.addNode)
        updateBtn.clicked.connect(self.updateNode)
        deleteBtn.clicked.connect(self.deleteNode)

        # 树
        self.tree = QTreeWidget()
        # 为树控件指定列数
        self.tree.setColumnCount(2)
        # 指定列标签
        self.tree.setHeaderLabels(['Key', 'Value'])

        # 根节点
        root = QTreeWidgetItem(self.tree)
        root.setText(0, 'root')  # 0代表第一列,即Key列,值为root
        root.setText(1, '0')

        # 添加子节点child1
        child1 = QTreeWidgetItem(root)
        child1.setText(0, 'child1')
        child1.setText(1, '1')

        # 添加子节点child2
        child2 = QTreeWidgetItem(root)
        child2.setText(0, 'child2')
        child2.setText(1, '2')

        # 为child2添加一个子节点child3
        child3 = QTreeWidgetItem(child2)
        child3.setText(0, 'child3')
        child3.setText(1, '3')

        # 信号和槽
        self.tree.clicked.connect(self.onTreeClicked)

        mainLayout=QVBoxLayout(self)
        mainLayout.addLayout(operatorLayout)
        mainLayout.addWidget(self.tree)
        self.setLayout(mainLayout)

    def onTreeClicked(self, index):  # index是被点击节点的索引
        item = self.tree.currentItem()  # 获得当前单击项
        print('当前处于第%d行' % index.row())  # 输出当前行(自己父节点的第几个值)
        print('key=%s,value=%s' % (item.text(0), item.text(1)))
        print()

    def addNode(self):
        print('添加节点')
        item=self.tree.currentItem()# 获得当前结点
        print('当前节点是:',item)
        node=QTreeWidgetItem(item)
        node.setText(0,'新节点')
        node.setText(1,'新值')

    def updateNode(self):
        print('修改节点')
        item=self.tree.currentItem()
        item.setText(0,'修改节点')
        item.setText(1,'值已经被修改')

    def deleteNode(self):
        print('删除节点')
        #防止item是root时,root无父结点报错,要使用下面的写法
        rootFather=self.tree.invisibleRootItem()#获得根节点root的不可见的父节点
        for item in self.tree.selectedItems():
            #父节点不为空
            (item.parent() or rootFather).removeChild(item)


if __name__=='__main__':
    app=QApplication(sys.argv)
    main=ModifyTree()
    main.show()
    sys.exit(app.exec_())

operation result:

 

 

Five. QTreeView control and system customization mode

Generally complex tree controls are written with QTreeView

Code:

import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *


if __name__=='__main__':
    app=QApplication(sys.argv)
    
    #显示目录结构的模型
    model=QDirModel()
    tree=QTreeView()
    tree.setModel(model)
    tree.setWindowTitle('QTreeView')
    tree.resize(600,400)
    tree.show()

    sys.exit(app.exec_())

operation result:

 

Guess you like

Origin blog.csdn.net/weixin_44593822/article/details/113567142