How to use parentItem method in fMBT

Best Python code snippet using fMBT_python

HDF5TreeViewModel.py

Source:HDF5TreeViewModel.py Github

copy

Full Screen

1#--------------------------------------------------------------------------2# File and Version Information:3# $Id$4#5# Description:6# Module HDF5TreeViewModel...7#8#------------------------------------------------------------------------9"""Makes QtGui.QStandardItemModel for QtGui.QTreeView10This software was developed for the SIT project. If you use all or 11part of it, please give an appropriate acknowledgment.12@see RelatedModule13@version $Id: template!python!py 4 2008-10-08 19:27:36Z salnikov $14@author Mikhail S. Dubrovin15"""16from __future__ import print_function17from __future__ import absolute_import18#------------------------------19# Module's version from CVS --20#------------------------------21__version__ = "$Revision: 4 $"22# $Source$23#--------------------------------24# Imports of standard modules --25#--------------------------------26import sys27from PyQt5 import QtCore, QtGui28from PyQt5.QtCore import Qt29import h5py30#-----------------------------31# Imports for other modules --32#-----------------------------33from . import ConfigParameters as cp34import AppUtils.AppDataPath as apputils35from HDF5Explorer.MQStandardItem import MQStandardItem36#---------------------37# Class definition --38#---------------------39try:40 QString = unicode41except NameError:42 # Python 343 QString = str44class HDF5TreeViewModel(QtGui.QStandardItemModel) :45 """Makes QtGui.QStandardItemModel for QtGui.QTreeView.46 """47 #----------------48 # Constructor --49 #----------------50 def __init__(self, parent=None):51 # !!!!! THE /data/ SUBDIRECTORY SHOULD BE OMITTED IN PATH !!!!!52 self.apppath_icon_folder_open = apputils.AppDataPath('HDF5Explorer/icons/folder_open.gif')53 self.apppath_icon_folder_closed = apputils.AppDataPath('HDF5Explorer/icons/folder_closed.gif')54 self.apppath_icon_data = apputils.AppDataPath('HDF5Explorer/icons/table.gif')55 self.icon_folder_open = QtGui.QIcon(self.apppath_icon_folder_open .path())56 self.icon_folder_closed = QtGui.QIcon(self.apppath_icon_folder_closed.path())57 self.icon_data = QtGui.QIcon(self.apppath_icon_data .path())58 QtGui.QStandardItemModel.__init__(self, parent)59 self.str_file = 'File'60 self.str_data = 'Data'61 self.str_group = 'Group'62 #self._model_example()63 self._model_hdf5_tree()64 #-------------------65 # Public methods --66 #-------------------67 #--------------------68 # Private methods --69 #--------------------70 def close(self) :71 print("HDF5TreeViewModel.close()")72 def _model_hdf5_tree(self) :73 """Puts the HDF5 file structure in the model tree"""74 fname = cp.confpars.dirName+'/'+cp.confpars.fileName75 print('Makes the tree view model for HDF5 file : ' + fname)76 f = h5py.File(fname, 'r') # open read-only77 self._begin_construct_tree(f)78 f.close()79 #self.sort(0, order=Qt.AscendingOrder)80 print('=== EOF ===')81 #---------------------82 def _begin_construct_tree(self, g):83 """Adds the input file/group/dataset (g) name and begin iterations on its content"""84 print("Add structure of the", end=' ')85 if isinstance(g,h5py.File): print("'File'", end=' ')86 elif isinstance(g,h5py.Group): print("'Group' from file", end=' ')87 elif isinstance(g,h5py.Dataset): print("'Dataset' from file", end=' ')88 print(g.file,"\n",g.name)89 self.parentItem = self.invisibleRootItem()90 self.parentItem.setAccessibleDescription(self.str_file)91 self.parentItem.setAccessibleText(g.name) # Root item does not show this text...92 #self.parentItem.setIcon(self.icon_folder_open) # Root item does not show icon...93 94 if isinstance(g,h5py.Dataset):95 print(offset, "(Dateset) len =", g.shape) #, subg.dtype96 item = MQStandardItem(QString(g.key()))97 item.setAccessibleDescription(self.str_data)98 self.parentItem.appendRow(item) 99 else:100 self.parentItem.sortChildren(0, order=Qt.DescendingOrder)101 self._add_group_to_tree(g,self.parentItem) # start recursions from here102 #---------------------103 def _add_group_to_tree(self, g, parentItem):104 """Adds content of the file/group/dataset iteratively, starting from the sub-groups of g"""105 try :106 d = dict(g)107 except h5py.h5e.BtreeError: 108 print(70*'!')109 print('ERROR: CORRUPTED HDF5 STRUCTURE !!!' + \110 '\nCAN NOT MAKE A DICTIONARY FROM THE GROUP d = dict(g):\n', g) 111 print('THIS GROUP IS MARKED AS UNRECOGNIZED IN THE TREE...')112 print(70*'!')113 item = MQStandardItem(QString('UNRECOGNIZED GROUP'))114 parentItem.appendRow(item)115 return116 117 list_keys = sorted(d.keys())118 list_vals = list(d.values())119 #print 'XXX list_keys =', list_keys 120 for key in list_keys:121 #for key,val in dict(g).iteritems():122 #subg = val123 subg = d[key]124 item = MQStandardItem(QString(key))125 #print ' k=', key, #," ", subg.name #, val, subg.len(), type(subg), 126 if isinstance(subg, h5py.Dataset):127 #print " (Dateset) len =", subg.shape #, subg.dtype128 item.setIcon(self.icon_data)129 item.setCheckable(True)130 item.setAccessibleDescription(self.str_data)131 item.setAccessibleText(str(key))132 parentItem.appendRow(item)133 134 elif isinstance(subg, h5py.Group):135 #print " (Group) len =",len(subg) 136 #offset_subg = offset + ' '137 item.setIcon(self.icon_folder_closed)138 item.setAccessibleDescription(self.str_group)139 item.setAccessibleText(str(key))140 parentItem.appendRow(item)141 self._add_group_to_tree(subg,item)142 parentItem.sortChildren(0, order=Qt.DescendingOrder)143 #---------------------144 #---------------------145 #---------------------146 #---------------------147 def getFullNameFromItem(self, item): 148 """Returns the full name in the HDF5 tree model for the given item"""149 ind = self.indexFromItem(item) 150 return self.getFullNameFromIndex(ind)151 #---------------------152 153 def getFullNameFromIndex(self, ind): 154 """Begin recursion from item with given ind(ex) and forms the full name in the self._full_name"""155 item = self.itemFromIndex(ind)156 self._full_name = item.text() 157 self._getFullName(ind) 158 return str(self._full_name) ### QString object is converted to str159 #---------------------160 def _getFullName(self, ind): 161 """Recursion from child to parent"""162 ind_par = self.parent(ind)163 if(ind_par.column() == -1) :164 item = self.itemFromIndex(ind)165 self._full_name = '/' + self._full_name166 #print 'Item full name :' + self._full_name167 return self._full_name168 else:169 item_par = self.itemFromIndex(ind_par)170 self._full_name = item_par.text() + '/' + self._full_name171 self._getFullName(ind_par)172 #---------------------173 #---------------------174 #---------------------175 #---------------------176 def set_all_group_icons(self,icon):177 """Iterates over the list of item in the QTreeModel and set icon for all groups"""178 self.new_icon = icon179 self._iteration_over_items_and_set_icon(self.parentItem)180 #---------------------181 def _iteration_over_items_and_set_icon(self,parentItem):182 """Recursive iteration over item children in the frame of the QtGui.QStandardItemModel"""183 if parentItem.accessibleDescription() == 'Group' :184 parentItem.setIcon(self.new_icon)185 186 if parentItem.hasChildren():187 for row in range(parentItem.rowCount()) :188 item = parentItem.child(row,0)189 self._iteration_over_items_and_set_icon(item) 190 #---------------------191 #---------------------192 #---------------------193 #---------------------194 def reset_checked_items(self):195 """Iterates over the list of item in the QTreeModel and uncheck all checked items"""196 self._iteration_over_items_and_uncheck(self.parentItem)197 #---------------------198 def _iteration_over_items_and_uncheck(self,parentItem):199 """Recursive iteration over item children in the frame of the QtGui.QStandardItemModel"""200 state = ['UNCHECKED', 'TRISTATE', 'CHECKED'][parentItem.checkState()]201 if state == 'CHECKED' or state == 'TRISTATE' :202 print(' Uncheck item.text():', parentItem.text())203 parentItem.setCheckState(0) # 0 means UNCHECKED204 205 if parentItem.hasChildren():206 for row in range(parentItem.rowCount()) :207 item = parentItem.child(row,0)208 self._iteration_over_items_and_uncheck(item) 209 #---------------------210 #---------------------211 #---------------------212 #---------------------213 def expand_checked_items(self,view):214 """Iterates over the list of item in the QTreeModel and expand all checked items"""215 self.view = view216 self._iteration_over_items_and_expand_checked(self.parentItem)217 #---------------------218 def _iteration_over_items_and_expand_checked(self,parentItem):219 """Recursive iteration over item children in the frame of the QtGui.QStandardItemModel"""220 state = ['UNCHECKED', 'TRISTATE', 'CHECKED'][parentItem.checkState()]221 if state == 'CHECKED' or state == 'TRISTATE' :222 print(' Expand item.text():', parentItem.text())223 #Now we have to expand all parent groups for this checked item...224 self._expand_parents(parentItem)225 226 if parentItem.hasChildren():227 for row in range(parentItem.rowCount()) :228 item = parentItem.child(row,0)229 self._iteration_over_items_and_expand_checked(item) 230 #---------------------231 def _expand_parents(self,item):232 item_parent = item.parent()233 ind_parent = self.indexFromItem(item_parent)234 if(ind_parent.column() != -1) :235 if item_parent.accessibleDescription() == 'Group' :236 self.view.expand(ind_parent)237 item_parent.setIcon(self.icon_folder_open)238 self._expand_parents(item_parent)239 #---------------------240 #---------------------241 #---------------------242 #---------------------243 def retreve_checked_items(self,list_of_checked_item_names):244 """Use the input list of items and check them in the tree model"""245 self.list_of_checked_item_names = list_of_checked_item_names246 for name in self.list_of_checked_item_names :247 print('Retreve the CHECKMARK for item', name) 248 self._iteration_over_items_and_check_from_list(self.parentItem) 249 #---------------------250 def _iteration_over_items_and_check_from_list(self,parentItem):251 """Recursive iteration over item children in the frame of the QtGui.QStandardItemModel"""252 if parentItem.isCheckable():253 item_name = self.getFullNameFromItem(parentItem)254 if item_name in self.list_of_checked_item_names :255 print(' Check the item:', item_name) # parentItem.text()256 parentItem.setCheckState(2) # 2 means CHECKED; 1-TRISTATE257 258 if parentItem.hasChildren():259 for row in range(parentItem.rowCount()) :260 item = parentItem.child(row,0)261 self._iteration_over_items_and_check_from_list(item) 262 #---------------------263 #---------------------264 #---------------------265 #---------------------266 267 def get_list_of_checked_item_names_for_model(self):268 """Get the list of checked item names for the self tree model"""269 list_of_checked_items = self.get_list_of_checked_items()270 return self.get_list_of_checked_item_names(list_of_checked_items)271 #---------------------272 273 def get_list_of_checked_item_names(self,list_of_checked_items):274 """Get the list of checked item names from the input list of items"""275 self.list_of_checked_item_names=[]276 print('The number of CHECKED items in the tree model =', len(self.list_of_checked_items))277 278 for item in list_of_checked_items :279 item_full_name = self.getFullNameFromItem(item)280 self.list_of_checked_item_names.append(item_full_name)281 print('Checked item :', item_full_name)282 283 return self.list_of_checked_item_names 284 #---------------------285 def get_list_of_checked_items(self):286 """Returns the list of checked item names in the QTreeModel"""287 self.list_of_checked_items=[]288 #self._iteration_over_tree_model_item_children_v1(self.parentItem)289 #self._iteration_over_tree_model_item_children_v2(self.parentItem)290 self._iteration_over_items_find_checked(self.parentItem)291 return self.list_of_checked_items292 #---------------------293 def _iteration_over_items_find_checked(self,parentItem):294 """Recursive iteration over item children in the frame of the QtGui.QStandardItemModel"""295 state = ['UNCHECKED', 'TRISTATE', 'CHECKED'][parentItem.checkState()]296 if state == 'CHECKED' :297 #print ' checked item.text():', parentItem.text()298 self.list_of_checked_items.append(parentItem)299 300 if parentItem.hasChildren():301 for row in range(parentItem.rowCount()) :302 item = parentItem.child(row,0)303 self._iteration_over_items_find_checked(item) 304 #---------------------305 #---------------------306 #---------------------307 #---------------------308 def _iteration_over_tree_model_item_children_v1(self,parentItem):309 """Recursive iteration over item children in the frame of the QtGui.QStandardItemModel"""310 parentIndex = self.indexFromItem(parentItem)311 print(' item.text():', parentItem.text(), end=' ')312 print(' row:', parentIndex.row(), end=' ') 313 print(' col:', parentIndex.column())314 if parentItem.hasChildren():315 Nrows = parentItem.rowCount()316 print(' rowCount:', Nrows)317 for row in range(Nrows) :318 item = parentItem.child(row,0)319 self._iteration_over_tree_model_item_children_v1(item) 320 #---------------------321 def _iteration_over_tree_model_item_children_v2(self,parentItem):322 """Recursive iteration over item children in the freame of the QtGui.QStandardItemModel"""323 print(' parentItem.text():', parentItem.text())324 if parentItem.hasChildren():325 list_of_items = parentItem.takeColumn(0) # THIS GUY REMOVES THE COLUMN !!!!!!!!326 parentItem.insertColumn(0, list_of_items) 327 for item in list_of_items : 328 self._iteration_over_tree_model_item_children_v2(item) 329 #---------------------330 def _model_example(self) :331 """Makes the model tree for example"""332 for k in range(0, 6):333 parentItem = self.invisibleRootItem()334 for i in range(0, k):335 item = MQStandardItem(QString("itemA %0 %1").arg(k).arg(i))336 item.setIcon(self.icon_data)337 item.setCheckable(True) 338 parentItem.appendRow(item)339 item = MQStandardItem(QString("itemB %0 %1").arg(k).arg(i))340 item.setIcon(self.icon_folder_closed)341 parentItem.appendRow(item)342 parentItem = item343 print('append item %s' % (item.text()))344#---------------------345# In case someone decides to run this module346#347if __name__ == "__main__" :348 349 sys.exit ( "Module is not supposed to be run as main module" )...

Full Screen

Full Screen

qtgroupboxpropertybrowser.py

Source:qtgroupboxpropertybrowser.py Github

copy

Full Screen

1#############################################################################2##3## Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).4## Contact: http:##www.qt-project.org/legal5##6## This file is part of the Qt Solutions component.7##8## $QT_BEGIN_LICENSE:BSD$9## You may use this file under the terms of the BSD license as follows:10##11## "Redistribution and use in source and binary forms, with or without12## modification, are permitted provided that the following conditions are13## met:14## * Redistributions of source code must retain the above copyright15## notice, this list of conditions and the following disclaimer.16## * Redistributions in binary form must reproduce the above copyright17## notice, this list of conditions and the following disclaimer in18## the documentation and/or other materials provided with the19## distribution.20## * Neither the name of Digia Plc and its Subsidiary(-ies) nor the names21## of its contributors may be used to endorse or promote products derived22## from this software without specific prior written permission.23##24##25## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS26## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT27## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR28## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT29## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,30## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT31## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,32## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY33## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT34## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE35## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."36##37## $QT_END_LICENSE$38##39#############################################################################40from qtpropertybrowser import QtAbstractPropertyBrowser41from PyQt5.QtCore import Qt, QTimer, QRect42from PyQt5.QtWidgets import (43 QGridLayout, QLabel, QGroupBox, QSizePolicy, QSpacerItem,44 QFrame45 )46from pyqtcore import (47 QList,48 QMap49 )50class WidgetItem():51 def __init__(self):52 self.widget = 0# can be null53 self.label = 054 self.widgetLabel = 055 self.groupBox = 056 self.layout = 057 self.line = 058 self.parent = None59 self.children = QList()60class QtGroupBoxPropertyBrowserPrivate():61 def __init__(self):62 self.q_ptr = None63 self.m_indexToItem = QMap()64 self.m_itemToIndex = QMap()65 self.m_widgetToItem = QMap()66 self.m_mainLayout = 067 self.m_children = QList()68 self.m_recreateQueue = QList()69 def createEditor(self, property, parent):70 return self.q_ptr.createEditor(property, parent)71 def init(self, parent):72 self.m_mainLayout = QGridLayout()73 parent.setLayout(self.m_mainLayout)74 item = QSpacerItem(0, 0, QSizePolicy.Fixed, QSizePolicy.Expanding)75 self.m_mainLayout.addItem(item, 0, 0)76 def slotEditorDestroyed(self):77 editor = self.q_ptr.sender()78 if (not editor):79 return80 if (not editor in self.m_widgetToItem.keys()):81 return82 self.m_widgetToItem[editor].widget = 083 self.m_widgetToItem.remove(editor)84 def slotUpdate(self):85 for item in self.m_recreateQueue:86 par = item.parent87 w = 088 l = 089 oldRow = -190 if (not par):91 w = self.q_ptr92 l = self.m_mainLayout93 oldRow = self.m_children.indexOf(item)94 else:95 w = par.groupBox96 l = par.layout97 oldRow = par.children.indexOf(item)98 if (self.hasHeader(par)):99 oldRow += 2100 if (item.widget):101 item.widget.setParent(w)102 elif (item.widgetLabel):103 item.widgetLabel.setParent(w)104 else:105 item.widgetLabel = QLabel(w)106 item.widgetLabel.setSizePolicy(QSizePolicy(QSizePolicy.Ignored, QSizePolicy.Fixed))107 item.widgetLabel.setTextFormat(Qt.PlainText)108 span = 1109 if (item.widget):110 l.addWidget(item.widget, oldRow, 1, 1, 1)111 elif (item.widgetLabel):112 l.addWidget(item.widgetLabel, oldRow, 1, 1, 1)113 else:114 span = 2115 item.label = QLabel(w)116 item.label.setSizePolicy(QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed))117 l.addWidget(item.label, oldRow, 0, 1, span)118 self.updateItem(item)119 self.m_recreateQueue.clear()120 def updateLater(self):121 QTimer.singleShot(0, self.q_ptr, self.slotUpdate())122 def propertyInserted(self, index, afterIndex):123 afterItem = self.m_indexToItem[afterIndex]124 parentItem = self.m_indexToItem.value(index.parent())125 newItem = WidgetItem()126 newItem.parent = parentItem127 layout = 0128 parentWidget = 0129 row = -1130 if (not afterItem):131 row = 0132 if (parentItem):133 parentItem.children.insert(0, newItem)134 else:135 self.m_children.insert(0, newItem)136 else:137 if (parentItem):138 row = parentItem.children.indexOf(afterItem) + 1139 parentItem.children.insert(row, newItem)140 else:141 row = self.m_children.indexOf(afterItem) + 1142 self.m_children.insert(row, newItem)143 if (parentItem and self.hasHeader(parentItem)):144 row += 2145 if (not parentItem):146 layout = self.m_mainLayout147 parentWidget = self.q_ptr148 else:149 if not parentItem.groupBox:150 self.m_recreateQueue.removeAll(parentItem)151 par = parentItem.parent152 w = 0153 l = 0154 oldRow = -1155 if (not par):156 w = self.q_ptr157 l = self.m_mainLayout158 oldRow = self.m_children.indexOf(parentItem)159 else:160 w = par.groupBox161 l = par.layout162 oldRow = par.children.indexOf(parentItem)163 if (self.hasHeader(par)):164 oldRow += 2165 parentItem.groupBox = QGroupBox(w)166 parentItem.layout = QGridLayout()167 parentItem.groupBox.setLayout(parentItem.layout)168 if (parentItem.label):169 l.removeWidget(parentItem.label)170 parentItem.label.close()171 parentItem.label = 0172 if (parentItem.widget):173 l.removeWidget(parentItem.widget)174 parentItem.widget.setParent(parentItem.groupBox)175 parentItem.layout.addWidget(parentItem.widget, 0, 0, 1, 2)176 parentItem.line = QFrame(parentItem.groupBox)177 elif (parentItem.widgetLabel):178 l.removeWidget(parentItem.widgetLabel)179 parentItem.widgetLabel.close()180 parentItem.widgetLabel = 0181 if (parentItem.line):182 parentItem.line.setFrameShape(QFrame.HLine)183 parentItem.line.setFrameShadow(QFrame.Sunken)184 parentItem.layout.addWidget(parentItem.line, 1, 0, 1, 2)185 l.addWidget(parentItem.groupBox, oldRow, 0, 1, 2)186 self.updateItem(parentItem)187 layout = parentItem.layout188 parentWidget = parentItem.groupBox189 newItem.label = QLabel(parentWidget)190 newItem.label.setSizePolicy(QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed))191 newItem.widget = self.createEditor(index.property(), parentWidget)192 if (not newItem.widget):193 newItem.widgetLabel = QLabel(parentWidget)194 newItem.widgetLabel.setSizePolicy(QSizePolicy(QSizePolicy.Ignored, QSizePolicy.Fixed))195 newItem.widgetLabel.setTextFormat(Qt.PlainText)196 else:197 newItem.widget.destroyed.connect(self.slotEditorDestroyed)198 self.m_widgetToItem[newItem.widget] = newItem199 self.insertRow(layout, row)200 span = 1201 if (newItem.widget):202 layout.addWidget(newItem.widget, row, 1)203 elif (newItem.widgetLabel):204 layout.addWidget(newItem.widgetLabel, row, 1)205 else:206 span = 2207 layout.addWidget(newItem.label, row, 0, 1, span)208 self.m_itemToIndex[newItem] = index209 self.m_indexToItem[index] = newItem210 self.updateItem(newItem)211 def propertyRemoved(self, index):212 item = self.m_indexToItem[index]213 self.m_indexToItem.remove(index)214 self.m_itemToIndex.remove(item)215 parentItem = item.parent216 row = -1217 if (parentItem):218 row = parentItem.children.indexOf(item)219 parentItem.children.removeAt(row)220 if (self.hasHeader(parentItem)):221 row += 2222 else:223 row = self.m_children.indexOf(item)224 self.m_children.removeAt(row)225 if (item.widget):226 item.widget.close()227 del item.widget228 if (item.label):229 item.label.close()230 del item.label231 if (item.widgetLabel):232 item.widgetLabel.close()233 del item.widgetLabel234 if (item.groupBox):235 item.groupBox.close()236 del item.groupBox237 if (not parentItem):238 self.removeRow(self.m_mainLayout, row)239 elif len(parentItem.children) > 0:240 self.removeRow(parentItem.layout, row)241 else:242 par = parentItem.parent243 l = 0244 oldRow = -1245 if (not par):246 l = self.m_mainLayout247 oldRow = self.m_children.indexOf(parentItem)248 else:249 l = par.layout250 oldRow = par.children.indexOf(parentItem)251 if (self.hasHeader(par)):252 oldRow += 2253 if (parentItem.widget):254 parentItem.widget.hide()255 parentItem.widget.setParent(0)256 elif (parentItem.widgetLabel):257 parentItem.widgetLabel.hide()258 parentItem.widgetLabel.setParent(0)259 else:260 #parentItem.widgetLabel = QLabel(w)261 pass262 l.removeWidget(parentItem.groupBox)263 parentItem.groupBox.close()264 parentItem.groupBox = 0265 parentItem.line = 0266 parentItem.layout = 0267 if (not parentItem in self.m_recreateQueue):268 self.m_recreateQueue.append(parentItem)269 self.updateLater()270 self.m_recreateQueue.removeAll(item)271 del item272 def insertRow(self, layout, row):273 itemToPos = QMap()274 idx = 0275 while (idx < layout.count()):276 r, c, rs, cs = layout.getItemPosition(idx)277 if (r >= row):278 itemToPos[layout.takeAt(idx)] = QRect(r + 1, c, rs, cs)279 else:280 idx += 1281 for it in itemToPos.keys():282 r = itemToPos[it]283 layout.addItem(it, r.x(), r.y(), r.width(), r.height())284 def removeRow(self, layout, row):285 itemToPos = QMap()286 idx = 0287 while (idx < layout.count()):288 r, c, rs, cs = layout.getItemPosition(idx)289 if (r > row):290 itemToPos[layout.takeAt(idx)] = QRect(r - 1, c, rs, cs)291 else:292 idx += 1293 for it in itemToPos.keys():294 r = itemToPos[it]295 layout.addItem(it, r.x(), r.y(), r.width(), r.height())296 def hasHeader(self, item):297 if (item.widget):298 return True299 return False300 def propertyChanged(self, index):301 item = self.m_indexToItem[index]302 self.updateItem(item)303 def updateItem(self, item):304 property = self.m_itemToIndex[item].property()305 if (item.groupBox):306 font = item.groupBox.font()307 font.setUnderline(property.isModified())308 item.groupBox.setFont(font)309 item.groupBox.setTitle(property.propertyName())310 item.groupBox.setToolTip(property.toolTip())311 item.groupBox.setStatusTip(property.statusTip())312 item.groupBox.setWhatsThis(property.whatsThis())313 item.groupBox.setEnabled(property.isEnabled())314 if (item.label):315 font = item.label.font()316 font.setUnderline(property.isModified())317 item.label.setFont(font)318 item.label.setText(property.propertyName())319 item.label.setToolTip(property.toolTip())320 item.label.setStatusTip(property.statusTip())321 item.label.setWhatsThis(property.whatsThis())322 item.label.setEnabled(property.isEnabled())323 if (item.widgetLabel):324 font = item.widgetLabel.font()325 font.setUnderline(False)326 item.widgetLabel.setFont(font)327 item.widgetLabel.setText(property.valueText())328 item.widgetLabel.setToolTip(property.valueText())329 item.widgetLabel.setEnabled(property.isEnabled())330 if (item.widget):331 font = item.widget.font()332 font.setUnderline(False)333 item.widget.setFont(font)334 item.widget.setEnabled(property.isEnabled())335 item.widget.setToolTip(property.valueText())336 #item.setIcon(1, property.valueIcon())337###338# \class QtGroupBoxPropertyBrowser339#340# \brief The QtGroupBoxPropertyBrowser class provides a QGroupBox341# based property browser.342#343# A property browser is a widget that enables the user to edit a344# given set of properties. Each property is represented by a label345# specifying the property's name, and an editing widget (e.g. a line346# edit or a combobox) holding its value. A property can have zero or347# more subproperties.348#349# QtGroupBoxPropertyBrowser provides group boxes for all nested350# properties, i.e. subproperties are enclosed by a group box with351# the parent property's name as its title. For example:352#353# \image qtgroupboxpropertybrowser.png354#355# Use the QtAbstractPropertyBrowser API to add, insert and remove356# properties from an instance of the QtGroupBoxPropertyBrowser357# class. The properties themselves are created and managed by358# implementations of the QtAbstractPropertyManager class.359#360# \sa QtTreePropertyBrowser, QtAbstractPropertyBrowser361###362###363# Creates a property browser with the given \a parent.364###365class QtGroupBoxPropertyBrowser(QtAbstractPropertyBrowser):366 def __init__(self, parent=None):367 super(QtGroupBoxPropertyBrowser, self).__init__(parent)368 self.d_ptr = QtGroupBoxPropertyBrowserPrivate()369 self.d_ptr.q_ptr = self370 self.d_ptr.init(self)371 ###372 # Destroys this property browser.373 #374 # Note that the properties that were inserted into this browser are375 # \e not destroyed since they may still be used in other376 # browsers. The properties are owned by the manager that created377 # them.378 #379 # \sa QtProperty, QtAbstractPropertyManager380 ###381 def __del__(self):382 for it in self.d_ptr.m_itemToIndex.keys():383 del it384 del self.d_ptr385 ###386 # \reimp387 ###388 def itemInserted(self, item, afterItem):389 self.d_ptr.propertyInserted(item, afterItem)390 ###391 # \reimp392 ###393 def itemRemoved(self, item):394 self.d_ptr.propertyRemoved(item)395 ###396 # \reimp397 ###398 def itemChanged(self, item):...

Full Screen

Full Screen

ItemViews_QTreeView_07_TreeModel.py

Source:ItemViews_QTreeView_07_TreeModel.py Github

copy

Full Screen

1#!/usr/bin/env python2# coding: utf-83# 예제 내용4# * QListView 기본 사용법5# * QAbstractListModel 을 이용한 사용자 모델 생성6# * 수정이 가능한 모델7import sys8from PyQt5.QtWidgets import QWidget9from PyQt5.QtWidgets import QTreeView10from PyQt5.QtWidgets import QBoxLayout11from PyQt5.QtWidgets import QAbstractItemView12from PyQt5.QtWidgets import QApplication13from PyQt5.QtWidgets import QComboBox14from PyQt5.QtWidgets import QItemDelegate15from PyQt5.QtWidgets import QStyleOptionViewItem16from PyQt5.QtGui import QStandardItem17from PyQt5.QtGui import QPainter18from PyQt5.QtCore import Qt19from PyQt5.QtCore import QAbstractItemModel20from PyQt5.QtCore import pyqtSlot21from PyQt5.QtCore import QVariant22from PyQt5.QtCore import QModelIndex23__author__ = "Deokyu Lim <hong18s@gmail.com>"24class TreeItem(object):25 def __init__(self, data, parent=None):26 self.parentItem = parent27 self.itemData = data28 self.childItems = []29 def appendChild(self, item):30 self.childItems.append(item)31 def child(self, row):32 return self.childItems[row]33 def childCount(self):34 return len(self.childItems)35 def columnCount(self):36 return len(self.itemData)37 def data(self, column):38 try:39 return self.itemData[column]40 except IndexError:41 return None42 def parent(self):43 return self.parentItem44 def row(self):45 if self.parentItem:46 return self.parentItem.childItems.index(self)47 return 048class TreeModel(QAbstractItemModel):49 def __init__(self, data, parent=None):50 super(TreeModel, self).__init__(parent)51 self.rootItem = TreeItem(("Properties", "Value"))52 self.setupModelData(data, self.rootItem)53 def columnCount(self, parent):54 if parent.isValid():55 return parent.internalPointer().columnCount()56 else:57 return self.rootItem.columnCount()58 def data(self, index: QModelIndex, role=None):59 if not index.isValid():60 return None61 item = index.internalPointer()62 if role == Qt.DisplayRole:63 return item.data(index.column())64 return QVariant()65 def flags(self, index):66 if not index.isValid():67 return Qt.NoItemFlags68 return Qt.ItemIsEnabled | Qt.ItemIsSelectable69 def headerData(self, section, orientation, role):70 if orientation == Qt.Horizontal and role == Qt.DisplayRole:71 return self.rootItem.data(section)72 return None73 def index(self, row, column, parent):74 if not self.hasIndex(row, column, parent):75 return QModelIndex()76 if not parent.isValid():77 parentItem = self.rootItem78 else:79 parentItem = parent.internalPointer()80 childItem = parentItem.child(row)81 if childItem:82 return self.createIndex(row, column, childItem)83 else:84 return QModelIndex()85 def parent(self, index):86 if not index.isValid():87 return QModelIndex()88 childItem = index.internalPointer()89 parentItem = childItem.parent()90 if parentItem == self.rootItem:91 return QModelIndex()92 return self.createIndex(parentItem.row(), 0, parentItem)93 def rowCount(self, parent):94 if parent.column() > 0:95 return 096 if not parent.isValid():97 parentItem = self.rootItem98 else:99 parentItem = parent.internalPointer()100 return parentItem.childCount()101 def _add_item(self, item):102 row = list()103 column = list()104 for sub_item in item['objects']:105 child = QStandardItem(sub_item['name'])106 col = QStandardItem(sub_item['value'])107 col.setCheckState(Qt.Checked if sub_item['value'] else Qt.Unchecked)108 col.setData(sub_item['editor'], Qt.UserRole+1)109 row.append(child)110 column.append(col)111 return row, column112 def setupModelData(self, items, parent):113 parents = [parent]114 parents[-1].appendChild(TreeItem(["option 1", "option 1 description"], parents[-1]))115 parents[-1].childItems[-1].appendChild(116 TreeItem(["enable", "True"], parents[-1].childItems[-1]))117 parents[-1].appendChild(TreeItem(["option 2", "option 2 description"], parents[-1]))118 parents[-1].childItems[-1].appendChild(119 TreeItem(["width", "100px"], parents[-1].childItems[-1]))120 parents[-1].childItems[-1].appendChild(121 TreeItem(["height", "120px"], parents[-1].childItems[-1]))122class Form(QWidget):123 def __init__(self):124 QWidget.__init__(self, flags=Qt.Widget)125 self.setWindowTitle("ItemView QListView")126 box = QBoxLayout(QBoxLayout.TopToBottom)127 # QTreeView 생성 및 설정128 view = QTreeView(self)129 view.setEditTriggers(QAbstractItemView.DoubleClicked)130 model = TreeModel(None)131 view.setModel(model)132 box.addWidget(view)133 self.setLayout(box)134if __name__ == "__main__":135 app = QApplication(sys.argv)136 excepthook = sys.excepthook137 sys.excepthook = lambda t, val, tb: excepthook(t, val, tb)138 form = Form()139 form.show()...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run fMBT automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful