Results 1 to 4 of 4

Thread: QTreeView: How to create objects from root items?

  1. #1
    Join Date
    Jun 2015
    Posts
    2
    Qt products
    Platforms
    Windows

    Default QTreeView: How to create objects from root items?

    Given a QTreeView that is supplied with a QStandardItemModel is it possible to create an object out of each root item in the model where all parent items linked to each root are contained in the created object? Furthermore, given a QTreeView set up with a model is it possible to save or access all data within the model, i assume yes by iterating somehow but the documentation at this point is just not helping; it leaves a lot unanswered if your a newbie. I've read all the documentation on QAbstractItemModel, QStandardItemModel, QTreeView, QAbstractItemView. I've read about the mimeData, mimeTypes, index, data, parent, rowCount, columnCount, createIndex et cetera methods in detail many times. Below i posted the code i have been using to experiment in hopes of figuring this stuff out. I auto add data when it's initialized to speed up the testing process but you can also add roots but entering text in the root box and pressing enter. To enter a parent enter text in parent box then click the item you would like it added to.

    This code is ready to run no outside resources needed besides the obvious, paste into an IDE and run. A pre-built model is loaded.

    Qt Code:
    1. # -*- coding: utf-8 -*-
    2.  
    3. # Form implementation generated from reading ui file 'Tree2.ui'
    4. #
    5. # Created: Thu Jun 18 17:54:24 2015
    6. # by: PyQt4 UI code generator 4.11.3
    7. #
    8. # WARNING! All changes made in this file will be lost!
    9. import sys
    10. from PyQt4 import QtCore, QtGui
    11.  
    12. try:
    13. _fromUtf8 = QtCore.QString.fromUtf8
    14. except AttributeError:
    15. def _fromUtf8(s):
    16. return s
    17.  
    18. try:
    19. _encoding = QtGui.QApplication.UnicodeUTF8
    20. def _translate(context, text, disambig):
    21. return QtGui.QApplication.translate(context, text, disambig, _encoding)
    22. except AttributeError:
    23. def _translate(context, text, disambig):
    24. return QtGui.QApplication.translate(context, text, disambig)
    25.  
    26. data1 = [("Name", [("a",[]), ("b",[]), ("c", [("e",[]), ("f", []) ])])]
    27.  
    28.  
    29. class Ui_MainWindow(QtGui.QMainWindow):
    30. def __init__(self):
    31. QtGui.QMainWindow.__init__(self)
    32. self.setupUi(self)
    33. self.indyTracker = 1
    34. self. stringBuilder = None
    35. self.boole = False
    36. self.treeBuilder = {}
    37. def setupUi(self, MainWindow):
    38. MainWindow.setObjectName(_fromUtf8("MainWindow"))
    39. MainWindow.resize(437, 529)
    40. self.centralwidget = QtGui.QWidget(MainWindow)
    41. self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
    42. self.verticalLayout_2 = QtGui.QVBoxLayout(self.centralwidget)
    43. self.verticalLayout_2.setObjectName(_fromUtf8("verticalLayout_2"))
    44. self.verticalLayout = QtGui.QVBoxLayout()
    45. self.verticalLayout.setObjectName(_fromUtf8("verticalLayout"))
    46.  
    47.  
    48. self.treeView = QtGui.QTreeView(self.centralwidget)
    49. self.treeView.setObjectName(_fromUtf8("treeView"))
    50. self.model = QtGui.QStandardItemModel()
    51. self.addItems(self.model, data1)
    52. self.treeView.setModel(self.model)
    53. self.model.setHorizontalHeaderLabels([self.tr("ROOT")])
    54.  
    55.  
    56. self.verticalLayout.addWidget(self.treeView)
    57. self.lineEdit_2 = QtGui.QLineEdit(self.centralwidget)
    58. self.lineEdit_2.setObjectName(_fromUtf8("lineEdit_2"))
    59. self.verticalLayout.addWidget(self.lineEdit_2)
    60. self.lineEdit = QtGui.QLineEdit(self.centralwidget)
    61. self.lineEdit.setText(_fromUtf8(""))
    62. self.lineEdit.setObjectName(_fromUtf8("lineEdit"))
    63. self.verticalLayout.addWidget(self.lineEdit)
    64. self.label = QtGui.QLabel(self.centralwidget)
    65. sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)
    66. sizePolicy.setHorizontalStretch(0)
    67. sizePolicy.setVerticalStretch(0)
    68. sizePolicy.setHeightForWidth(self.label.sizePolicy().hasHeightForWidth())
    69. self.label.setSizePolicy(sizePolicy)
    70. self.label.setAutoFillBackground(True)
    71. self.label.setFrameShape(QtGui.QFrame.Box)
    72. self.label.setFrameShadow(QtGui.QFrame.Raised)
    73. self.label.setLineWidth(3)
    74. self.label.setMidLineWidth(1)
    75. self.label.setText(_fromUtf8(""))
    76. self.label.setWordWrap(True)
    77. self.label.setOpenExternalLinks(True)
    78. self.label.setObjectName(_fromUtf8("label"))
    79. self.verticalLayout.addWidget(self.label)
    80. self.verticalLayout_2.addLayout(self.verticalLayout)
    81. MainWindow.setCentralWidget(self.centralwidget)
    82. self.menubar = QtGui.QMenuBar(MainWindow)
    83. self.menubar.setGeometry(QtCore.QRect(0, 0, 437, 21))
    84. self.menubar.setObjectName(_fromUtf8("menubar"))
    85. MainWindow.setMenuBar(self.menubar)
    86. self.statusbar = QtGui.QStatusBar(MainWindow)
    87. self.statusbar.setObjectName(_fromUtf8("statusbar"))
    88. MainWindow.setStatusBar(self.statusbar)
    89.  
    90. self.retranslateUi(MainWindow)
    91. QtCore.QMetaObject.connectSlotsByName(MainWindow)
    92.  
    93. def retranslateUi(self, MainWindow):
    94. MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow", None))
    95. self.lineEdit_2.setPlaceholderText(_translate("MainWindow", "Parent/Child - Press return to Add", None))
    96. self.lineEdit.setPlaceholderText(_translate("MainWindow", "Root Index - Press Return to Add", None))
    97.  
    98. self.lineEdit.returnPressed.connect(self.addAROOT)
    99. self.treeView.clicked.connect(self.addParents)
    100. #self.treeView.clicked.connect(self.modelIndexDefiner)
    101. self.treeView.clicked.connect(self.createIndex)
    102.  
    103.  
    104.  
    105. def addAROOT(self):
    106. parent = self.lineEdit.text()
    107. self.model.appendRow(QtGui.QStandardItem(parent))
    108.  
    109. @QtCore.pyqtSlot(QtCore.QAbstractItemModel)
    110. def addParents(self, index):
    111. selectedItem = index.model().itemFromIndex(index)
    112. if self.lineEdit_2.text() == "":
    113. errorHandle()
    114. else:
    115. selectedItem.appendRow(QtGui.QStandardItem(self.lineEdit_2.text()))
    116. self.lineEdit.clear()
    117. self.lineEdit_2.clear()
    118.  
    119.  
    120.  
    121.  
    122. @QtCore.pyqtSlot(QtCore.QAbstractItemModel)
    123. def modelIndexDefiner(self, index):
    124. childFlag = index.model().hasChildren(index)
    125. currentIndex = index.parent()
    126. currentItem = index.data()
    127. originalItem = currentItem
    128.  
    129.  
    130.  
    131. @QtCore.pyqtSlot(QtCore.QAbstractItemModel)
    132. def createIndex(self, index):
    133. selectedItem1 = index.model().itemFromIndex(index)
    134. selectedItem2 = index.parent()
    135. getRow = selectedItem1.rowCount()
    136. getColumn = selectedItem1.columnCount()
    137. if not selectedItem2.isValid():
    138. self.label.setText(("\t" + selectedItem1.text() + "\t" + str(getRow) + "\t" + str(getColumn))
    139. + "\n" + "\tROOT")
    140. else:
    141. self.label.setText(("\t" + selectedItem1.text() + "\t" + str(getRow) + "\t" + str(getColumn))
    142. + "\n\tPARENT")
    143.  
    144. @QtCore.pyqtSlot(QtCore.QAbstractItemModel)
    145. def createRoot(self, index):
    146. self.selectedItem = index.model().itemFromIndex(index)
    147. self.parentCheck = index.parent()
    148. if not self.parentCheck.isValid():
    149. print("ROOT")
    150.  
    151.  
    152.  
    153. def addItems(self, parent, elements):
    154.  
    155. for text, children in elements:
    156. item = QtGui.QStandardItem(text)
    157. parent.appendRow(item)
    158. if children:
    159. self.addItems(item, children)
    160. class errorHandle():
    161. def __init__(self):
    162. pass
    163.  
    164.  
    165.  
    166.  
    167.  
    168. if __name__ == '__main__':
    169. app = QtGui.QApplication(sys.argv)
    170. mainWin = Ui_MainWindow()
    171. mainWin.show()
    172. sys.exit(app.exec())
    To copy to clipboard, switch view to plain text mode 
    Last edited by ficaras0; 23rd June 2015 at 22:14.

  2. #2
    Join Date
    Jan 2006
    Location
    Graz, Austria
    Posts
    8,416
    Thanks
    37
    Thanked 1,544 Times in 1,494 Posts
    Qt products
    Qt3 Qt4 Qt5
    Platforms
    Unix/X11 Windows

    Default Re: QTreeView: How to create objects from root items?

    Quote Originally Posted by ficaras0 View Post
    Given a QTreeView that is supplied with a QStandardItemModel is it possible to create an object out of each root item in the model where all parent items linked to each root are contained in the created object?
    No idea what you mean.
    Maybe provide an example of the tree and the desired result?

    Quote Originally Posted by ficaras0 View Post
    Furthermore, given a QTreeView set up with a model is it possible to save or access all data within the model
    1) You start with the invalid model index.
    2) You ask the model for the row count using that index
    3) You iterate over the range from 0 to row count, asking the model for the index with the model index you already have as a parent
    4) You recurse with the new index, go to (2)

    Cheers,
    _

  3. #3
    Join Date
    Jun 2015
    Posts
    2
    Qt products
    Platforms
    Windows

    Default Re: QTreeView: How to create objects from root items?

    I will edit with a comparison to make it more clear, also giving your solution a try.


    Added after 19 minutes:


    Quote Originally Posted by anda_skoa View Post
    asking the model for the index with the model index you already have as a parent
    This is the only part i'm not quite understanding, what you say makes sense i just don't understand how to implement it.
    Where would i go from here

    Qt Code:
    1. @QtCore.pyqtSlot(QtCore.QAbstractItemModel)
    2. def createRoot(self, index, parent = QtCore.QModelIndex()):
    3. self.selectedItem = index.model().itemFromIndex(index)
    4. self.parentCheck = index.parent()
    5. self.modelIdx = index.model()
    6. if not self.parentCheck.isValid():
    7. rowCount = self.selectedItem.rowCount()
    8. for child in range(0, rowCount):
    To copy to clipboard, switch view to plain text mode 
    Last edited by ficaras0; 23rd June 2015 at 22:31.

  4. #4
    Join Date
    Jan 2006
    Location
    Graz, Austria
    Posts
    8,416
    Thanks
    37
    Thanked 1,544 Times in 1,494 Posts
    Qt products
    Qt3 Qt4 Qt5
    Platforms
    Unix/X11 Windows

    Default Re: QTreeView: How to create objects from root items?

    I am not sure what your code snippet is supposed to do, but it is not what I described.

    1) create a function that gets a QModelndex as its argument
    2) in that function call the model's rowCount() with the given argument
    3) loop over the range of rows
    4) in the loop get the index for the current row
    5) call the function recursively

    Cheers,
    _

Similar Threads

  1. how to create folder in root directory using QT
    By iswaryasenthilkumar in forum Newbie
    Replies: 1
    Last Post: 24th February 2015, 17:21
  2. Need to remove root node from QTreeView
    By tescik in forum Qt Programming
    Replies: 4
    Last Post: 24th April 2014, 10:54
  3. How to create root node inQDirModel
    By deepak in forum Qt Programming
    Replies: 1
    Last Post: 29th August 2012, 08:03
  4. Replies: 7
    Last Post: 7th December 2010, 05:36
  5. QTreeView: include root in tree?
    By meter in forum Newbie
    Replies: 2
    Last Post: 14th June 2010, 13:59

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
Digia, Qt and their respective logos are trademarks of Digia Plc in Finland and/or other countries worldwide.