Найти - Пользователи
Полная версия: PyQT4 TreeModel
Начало » GUI » PyQT4 TreeModel
1
annndrey
Добрый день. Нет ли у кого ссылки на пример стандартной TreeModel?
В пример, идущий с документацией, что-то не могу вникнуть…

Вкратце ситуация такова:
после запроса база возвращает результат в следующем виде:

[
[A, ],
[B,],
.
.
.
[N,]
]

И теперь надо как-то передать это в TreeView, чтобы получилось примерно следующее:

A
|
+—a
+—b
+—c
|
B
+
|
+—a
+—b
+—c

итд…

Прошу ткнуть меня носом, куда смотерть…


Спасибо.
villager
тоже понадобилось :)
примеров и вопросов много, а понять ничего не мог
убил сутки, и вот результат:
import os
import sys
from PyQt4.QtSql import *
from PyQt4.QtGui import *

db=None

from PyQt4.QtCore import *
from PyQt4.QtGui import *

class zzNode(object):
def __init__(self, parent, uid, txt):
super(zzNode, self).__init__()
self.parent=parent
self.uid=uid
self.txt=txt
self.child=[]
cursor=db.exec_("select * from treetest where parent_uid=%s" % self.uid)
while cursor.next():
childId=int(cursor.record().field("uid").value().toString())
self.child.append(zzNode(self, childId, cursor.record().field("text").value().toString()))
def childCount(self):
return len(self.child)

class TreeOfTableModel(QAbstractItemModel):
def __init__(self, parent=None):
super(TreeOfTableModel, self).__init__(parent)
self.columns = 2
self.headers = ["key", "value"]
self.rootItem=zzNode(None, 0, "root")

def rowCount(self, parent):
if parent.column() > 0: return 0
if not parent.isValid():
parentItem = self.rootItem
else:
parentItem = parent.internalPointer()
return parentItem.childCount()

def columnCount(self, parent):
return self.columns

def data(self, index, role):
if role == Qt.DisplayRole:
tmp=index.internalPointer().child
if index.column()==0:
return index.internalPointer().uid
else:
return QVariant(index.internalPointer().txt)
else:
return QVariant()

def headerData(self, section, orientation, role):
if orientation == Qt.Horizontal and role == Qt.DisplayRole:
return QVariant(self.headers[section])
return QVariant()

def index(self, row, column, parent):
if not self.hasIndex(row, column, parent):
return QModelIndex()
if not parent.isValid():
parentItem = self.rootItem
else:
parentItem = parent.internalPointer()
childItem = parentItem.child[row]
if childItem:
return self.createIndex(row, column, childItem)
else:
return QtCore.QModelIndex()

def parent(self, child):
node = child.internalPointer()
if node is None:
return QModelIndex()
parent = node.parent
if parent is None:
return QModelIndex()
grandparent = parent.parent
if grandparent is None:
return QModelIndex()
row = grandparent.child.index(parent)
return self.createIndex(row, 0, parent)


class TreeOfTableWidget(QTreeView):
def __init__(self):
super(TreeOfTableWidget, self).__init__()
self.setSelectionBehavior(QTreeView.SelectItems)
self.setUniformRowHeights(True)
model = TreeOfTableModel(self)
self.setModel(model)

class MainForm(QMainWindow):
def __init__(self):
super(MainForm, self).__init__()
self.treeWidget = TreeOfTableWidget()
self.setCentralWidget(self.treeWidget)
QShortcut(QKeySequence("Escape"), self, self.close)
self.setWindowTitle("TreeViewExample")

app = QApplication(sys.argv)

db=QSqlDatabase.addDatabase("QSQLITE")
db.setDatabaseName(":memory:")
db.open()
db.exec_("create table treetest (uid int primary key, parent_uid int , text char)")
db.exec_("insert into treetest (uid,parent_uid,text) values (%s,%s,'%s')" % (1, 0, "z01"))
db.exec_("insert into treetest (uid,parent_uid,text) values (%s,%s,'%s')" % (2, 0, "z02"))
db.exec_("insert into treetest (uid,parent_uid,text) values (%s,%s,'%s')" % (3, 0, "z03"))
db.exec_("insert into treetest (uid,parent_uid,text) values (%s,%s,'%s')" % (4, 1, "z00-4"))
db.exec_("insert into treetest (uid,parent_uid,text) values (%s,%s,'%s')" % (5, 1, "z00-5"))
db.exec_("insert into treetest (uid,parent_uid,text) values (%s,%s,'%s')" % (6, 2, "z00-6"))
db.exec_("insert into treetest (uid,parent_uid,text) values (%s,%s,'%s')" % (7, 2, "z01-7"))
db.exec_("insert into treetest (uid,parent_uid,text) values (%s,%s,'%s')" % (8, 7, "z01-8"))
db.exec_("insert into treetest (uid,parent_uid,text) values (%s,%s,'%s')" % (9, 7, "z02-9"))
db.exec_("insert into treetest (uid,parent_uid,text) values (%s,%s,'%s')" % (10, 3, "z03-10"))
db.exec_("insert into treetest (uid,parent_uid,text) values (%s,%s,'%s')" % (11, 10, "z03-11"))
db.exec_("insert into treetest (uid,parent_uid,text) values (%s,%s,'%s')" % (12, 11, "z03-12"))
db.commit()

form = MainForm()
form.resize(750, 550)
form.show()
app.exec_()
annndrey
И да, я таки нашел решение (идея отсюда: http://www.mail-archive.com/pyqt@riverbankcomputing.com/msg19400.html)

   1. class TreeModel(QtCore.QAbstractItemModel):  
2. def __init__(self, data, parent=None):
3. super(TreeModel, self).__init__(parent)
4. self.parents=[]
5. self.dbdata = data
6. self.rootItem = TreeItem([u"NameOfColumn"])
7. self.setupModelData(self.dbdata, self.rootItem)
8.
9. def setData(self, index, value, role):
10. if index.isValid() and role == QtCore.Qt.EditRole:
11.
12. prev_value = self.getValue(index)
13.
14. item = index.internalPointer()
15.
16. item.setData(unicode(value.toString()))
17.
18. return True
19. else:
20. return False
21.
22. def removeRows(self, position=0, count=1, parent=QtCore.QModelIndex()):
23.
24. node = self.nodeFromIndex(parent)
25. self.beginRemoveRows(parent, position, position + count - 1)
26. node.childItems.pop(position)
27. self.endRemoveRows()
28.
29. def nodeFromIndex(self, index):
30. if index.isValid():
31. return index.internalPointer()
32. else:
33. return self.rootItem
34.
35. def getValue(self, index):
36. item = index.internalPointer()
37. return item.data(index.column())
38.
39. def columnCount(self, parent):
40. if parent.isValid():
41. return parent.internalPointer().columnCount()
42. else:
43. return self.rootItem.columnCount()
44.
45. def data(self, index, role):
46. if not index.isValid():
47. return None
48. if role != QtCore.Qt.DisplayRole:
49. return None
50.
51. item = index.internalPointer()
52. return QtCore.QVariant(item.data(index.column()))
53.
54. def flags(self, index):
55. if not index.isValid():
56. return QtCore.Qt.NoItemFlags
57.
58. return QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEditable
59.
60. def headerData(self, section, orientation, role):
61. if orientation == QtCore.Qt.Horizontal and role == QtCore.Qt.DisplayRole:
62. return QtCore.QVariant(self.rootItem.data(section)[0])
63.
64. return None
65.
66. def index(self, row, column, parent):
67.
68. if row < 0 or column < 0 or row >= self.rowCount(parent) or column >= self.columnCount(parent):
69. return QtCore.QModelIndex()
70.
71. if not parent.isValid():
72. parentItem = self.rootItem
73. else:
74. parentItem = parent.internalPointer()
75.
76. childItem = parentItem.child(row)
77. if childItem:
78. return self.createIndex(row, column, childItem)
79. else:
80. return QtCore.QModelIndex()
81.
82. def parent(self, index):
83. if not index.isValid():
84. return QtCore.QModelIndex()
85.
86. childItem = index.internalPointer()
87. parentItem = childItem.parent()
88.
89. if parentItem == self.rootItem:
90. return QtCore.QModelIndex()
91.
92. return self.createIndex(parentItem.row(), 0, parentItem)
93.
94. def rowCount(self, parent):
95. if parent.column() > 0:
96. return 0
97.
98. if not parent.isValid():
99. parentItem = self.rootItem
100. else:
101. parentItem = parent.internalPointer()
102.
103. return parentItem.childCount()
104.
105. def setupModelData(self, lines, parent):
106. ind = []
107. self.parents.append(parent)
108. ind.append(0)
109. col_numb=parent.columnCount()
110. numb = 0
111.
112. for line in lines:
113. numb+=1
114. lineData=line[0]
115. self.parents[-1].appendChild(TreeItem(lineData, self.parents[-1]))
116.
117. columnData = line[1]
118.
119. self.parents.append(self.parents[-1].child(self.parents[-1].childCount() - 1))
120.
121. for j in columnData:
122. self.parents[-1].appendChild(TreeItem(j, self.parents[-1]))
123. if len(self.parents) > 0:
124. self.parents.pop()
125.
126. class TreeItem(object):
127. def __init__(self, data, parent=None):
128. self.parentItem = parent
129. self.itemData = data
130. self.childItems = []
131.
132. def appendChild(self, item):
133. self.childItems.append(item)
134.
135. def child(self, row):
136. return self.childItems[row]
137.
138. def childCount(self):
139. return len(self.childItems)
140.
141. def columnCount(self):
142. return len(self.itemData)
143.
144. def data(self, column):
145. try:
146. return self.itemData
147.
148. except IndexError:
149. return None
150.
151. def parent(self):
152. return self.parentItem
153.
154. def row(self):
155. if self.parentItem:
156. return self.parentItem.childItems.index(self)
157.
158. return 0
159. def setData(self, data):
160. self.itemData = data
annndrey
Не пойму только, как сделать поддержку более одного столбца в списке…
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Powered by DjangoBB