Here is the link on other SO question QTreeView with custom items where is QTreeView example.
Please, can anyone explain me at this example, how to save tree structu
Your question is quite unclear, because you don't say what form you want the tree structure saved in.
Assuming that you don't really care, and that XML would be acceptable, you could take a look at the Simple DOM Model Example from the Qt docs.
Most of the examples from the Qt docs have been ported to PyQt, and are provided with the source code, which can be downloaded from here. The Simple DOM Model example can be found under examples/itemviews
.
EDIT:
I overlooked that you were using PySide. The equivalent ported examples for PySide can be found here, or in the PySide source code under sources/pyside-examples/examples/itemviews
.
UPDATE:
Here's a simple example which uses xml.etree to serialize the tree:
import sip
sip.setapi('QString', 2)
from xml.etree import cElementTree as etree
from PyQt4 import QtGui, QtCore
class Window(QtGui.QWidget):
def __init__(self, xml):
QtGui.QWidget.__init__(self)
self.tree = QtGui.QTreeWidget(self)
self.tree.header().hide()
self.importTree(xml)
self.button = QtGui.QPushButton('Export', self)
self.button.clicked[()].connect(self.exportTree)
layout = QtGui.QVBoxLayout(self)
layout.addWidget(self.tree)
layout.addWidget(self.button)
def importTree(self, xml):
def build(item, root):
for element in root.getchildren():
child = QtGui.QTreeWidgetItem(
item, [element.attrib['text']])
child.setFlags(
child.flags() | QtCore.Qt.ItemIsEditable)
build(child, element)
item.setExpanded(True)
root = etree.fromstring(xml)
build(self.tree.invisibleRootItem(), root)
def exportTree(self):
def build(item, root):
for row in range(item.childCount()):
child = item.child(row)
element = etree.SubElement(
root, 'node', text=child.text(0))
build(child, element)
root = etree.Element('root')
build(self.tree.invisibleRootItem(), root)
from xml.dom import minidom
print(minidom.parseString(etree.tostring(root)).toprettyxml())
if __name__ == '__main__':
import sys
app = QtGui.QApplication(sys.argv)
window = Window("""\
""")
window.setGeometry(800, 300, 300, 300)
window.show()
sys.exit(app.exec_())