您的位置:首页 > 编程语言 > Qt开发

PyQt学习笔记(16)——QTreeWidget

2015-04-17 09:32 295 查看
http://blog.sina.com.cn/s/blog_4b5039210100h6co.html

参考资料:Qt
documentation online(因为这个帮助文档是基于C++做的,里面的语句是C++写的,不过因为PyQt做了很好的移植,方法的名称,参数等等基本都可以在python中套用)

QTreeWidget的继承关系如下图:







The QTreeWidget class provides a tree view that uses a predefined tree model.

因为继承关系是QAbstractItemView->QTreeView->QTreeWidget
,所以和QTableWidget很多地方是类似的。

如果需要特殊的模式,比如显示硬盘信息及内部文件的dir模式等,都需要用QTreeView,而不是用QTreeWidget。

和QTableWidget类似,一般步骤是先创建一个QTreeWidget实例,然后设置列数,

然后再添加头。

# !/usr/bin/python

import sys

from PyQt4.QtGui import *

from PyQt4.QtCore import *

class TreeWidget(QMainWindow):

def __init__(self,parent=None):

QWidget.__init__(self,parent)

self.setWindowTitle('TreeWidget')

self.tree = QTreeWidget()

self.tree.setColumnCount(2)

self.tree.setHeaderLabels(['Key','Value'])

root= QTreeWidgetItem(self.tree)

root.setText(0,'root')

child1 = QTreeWidgetItem(root)

child1.setText(0,'child1')

child1.setText(1,'name1')

child2 = QTreeWidgetItem(root)

child2.setText(0,'child2')

child2.setText(1,'name2')

child3 = QTreeWidgetItem(root)

child3.setText(0,'child3')

child4 = QTreeWidgetItem(child3)

child4.setText(0,'child4')

child4.setText(1,'name4')

self.tree.addTopLevelItem(root)

self.setCentralWidget(self.tree)

app = QApplication(sys.argv)

tp = TreeWidget()

tp.show()

app.exec_()



结果如下







其中的QtreeWidgetItem就是一层层的添加的,其实还是不太方便的。



在应用程序中一般不是这样来创建QTreeView的,特别是比较复杂的Tree,一般都是通过QTreeView来实现而不是QTreeWidget来实现的。

这种与QTreeWidget最大的区别就是,我们自己来定制模式,当然也有些系统提供给我们的模式,比如我们的文件系统盘的树列表,比如下面的:

import sys

from PyQt4 import QtCore, QtGui

if __name__ == "__main__":

app = QtGui.QApplication(sys.argv)

model = QtGui.QDirModel() #系统给我们提供的

tree = QtGui.QTreeView()

tree.setModel(model)

tree.setWindowTitle(tree.tr("Dir View"))

tree.resize(640, 480)

tree.show()

sys.exit(app.exec_())

结果如下所示:







所以一般的我们自己定制模式,步骤如下:

import sys

from PyQt4 import QtCore, QtGui

if __name__ == "__main__":

app = QtGui.QApplication(sys.argv)

model = TreeModel(需要处理的数据)

view = QtGui.QTreeView()

view.setModel(model)

view.setWindowTitle("Simple Tree Model")

view.show()

sys.exit(app.exec_())

其中的TreeModel类是我们自己写的,如何显示我们的数据,可以查看相关资料。



我的更多文章:

PyQt学习笔记(15)——QFileDialog

(2010-03-09
09:01:38)

PyQt学习笔记(14)——布局管理

(2010-03-08
09:32:35)

PyQt学习笔记(12)——QSetting

(2010-03-05
10:33:15)

PyQt学习笔记(11)——QSplitter分割窗口

(2010-03-04
09:03:28)

PyQt学习笔记(10)——Events and Signals(2010-03-03
17:56:59)

PyQt学习笔记(9)——Qt Designer(3)(2010-02-20
12:29:30)

PyQt学习笔记(8)——Qt Designer(2)

(2010-02-20
12:22:13)

PyQt学习笔记(7)——Qt Designer(1)

(2010-02-20
12:13:33)

PyQt学习笔记(6)——Actions and Key Sequences(2010-02-20
09:40:24)

PyQt学习笔记(5)——Mian Window

(2010-02-20
09:37:46)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: