How to use rootItem method in fMBT

Best Python code snippet using fMBT_python

ProtocolTreeModel.py

Source:ProtocolTreeModel.py Github

copy

Full Screen

1from PyQt5.QtCore import QAbstractItemModel, pyqtSignal, QModelIndex, Qt, QMimeData2from PyQt5.QtGui import QIcon, QFont3from PyQt5.QtWidgets import QMessageBox, QWidget4from urh.models.ProtocolTreeItem import ProtocolTreeItem5from urh.signalprocessing.ProtocolAnalyzer import ProtocolAnalyzer6from urh.signalprocessing.ProtocolGroup import ProtocolGroup7from urh.util.Logger import logger8class ProtocolTreeModel(QAbstractItemModel):9 item_dropped = pyqtSignal()10 group_deleted = pyqtSignal(int, int)11 proto_to_group_added = pyqtSignal(int)12 group_added = pyqtSignal(QModelIndex)13 def __init__(self, controller, parent=None):14 self.rootItem = ProtocolTreeItem(None, None)15 self.rootItem.addGroup()16 self.controller = controller17 super().__init__(parent)18 @property19 def protocols(self):20 """21 :rtype: dict[int, list of ProtocolAnalyzer]22 """23 result = {}24 for i, group in enumerate(self.rootItem.children):25 result[i] = [child.protocol for child in group.children]26 return result27 @property28 def ngroups(self):29 return self.rootItem.childCount()30 @property31 def groups(self):32 """33 :rtype: list of ProtocolGroup34 """35 return [self.group_at(i) for i in range(self.ngroups)]36 @property37 def protocol_tree_items(self):38 """39 :rtype: dict[int, list of ProtocolTreeItem]40 """41 result = {}42 for i, group in enumerate(self.rootItem.children):43 result[i] = [child for child in group.children]44 return result45 def group_at(self, index: int) -> ProtocolGroup:46 return self.rootItem.child(index).group47 def update(self):48 self.beginResetModel()49 self.endResetModel()50 def get_group_id_for_index(self, index: QModelIndex) -> int:51 item = self.getItem(index)52 if item.parent() == self.rootItem:53 return self.rootItem.index_of(item)54 elif item == self.rootItem:55 return self.ngroups - 1 # Last group when dropped on root56 else:57 return self.rootItem.index_of(item.parent()) # Item is Protocol58 def getItem(self, index: QModelIndex) -> ProtocolTreeItem:59 if index.isValid():60 item = index.internalPointer()61 if item:62 return item63 return self.rootItem64 def rowCount(self, parent: QModelIndex = None, *args, **kwargs):65 parent_item = self.getItem(parent)66 return parent_item.childCount()67 def columnCount(self, parent: QModelIndex = None, *args, **kwargs):68 return 169 def index(self, row: int, column: int, parent=None, *args, **kwargs):70 if parent is None:71 return QModelIndex()72 parent_item = self.getItem(parent)73 child_item = parent_item.child(row)74 if child_item:75 return self.createIndex(row, column, child_item)76 else:77 return QModelIndex()78 def parent(self, index: QModelIndex = None):79 if not index.isValid():80 return QModelIndex()81 child_item = self.getItem(index)82 try:83 parent_item = child_item.parent()84 except AttributeError:85 return QModelIndex()86 if parent_item == self.rootItem or parent_item is None:87 return QModelIndex()88 return self.createIndex(parent_item.indexInParent(), 0, parent_item)89 def data(self, index: QModelIndex, role=None):90 item = self.getItem(index)91 if role == Qt.DisplayRole:92 return item.data()93 elif role == Qt.DecorationRole and item.is_group:94 return QIcon.fromTheme("folder")95 elif role == Qt.CheckStateRole:96 return item.show97 elif role == Qt.FontRole:98 if item.is_group and self.rootItem.index_of(item) in self.controller.active_group_ids:99 font = QFont()100 font.setBold(True)101 return font102 elif item.protocol in self.controller.selected_protocols:103 font = QFont()104 font.setBold(True)105 return font106 elif role == Qt.ToolTipRole:107 return item.data()108 def setData(self, index: QModelIndex, value, role=None):109 item = self.getItem(index)110 if role == Qt.EditRole and len(value) > 0:111 item.setData(value)112 return True113 elif role == Qt.CheckStateRole:114 item.show = value115 return True116 return False117 def add_protocol(self, protocol: ProtocolAnalyzer, group_id=0):118 if group_id >= self.ngroups:119 group_id = 0120 self.beginResetModel()121 self.rootItem.child(group_id).addProtocol(protocol)122 self.endResetModel()123 self.proto_to_group_added.emit(group_id)124 return self.groups[group_id]125 def remove_protocol(self, protocol: ProtocolAnalyzer):126 self.beginResetModel()127 result = False128 for group in self.rootItem.children:129 if group.removeProtocol(protocol):130 result = True131 break132 self.endResetModel()133 return result134 def flags(self, index: QModelIndex):135 if not index.isValid():136 return Qt.ItemIsDropEnabled137 return Qt.ItemIsEditable | Qt.ItemIsEnabled | Qt.ItemIsSelectable | \138 Qt.ItemIsUserCheckable | Qt.ItemIsDragEnabled | Qt.ItemIsDropEnabled139 def supportedDragActions(self):140 return Qt.MoveAction | Qt.CopyAction141 def mimeTypes(self):142 return ['text/plain', 'text/uri-list']143 def mimeData(self, indexes):144 data = ''145 for index in indexes:146 parent_item = self.getItem(index.parent())147 if parent_item == self.rootItem:148 data += "{0},{1},{2}/".format(index.row(), index.column(), -1)149 else:150 data += "{0},{1},{2}/".format(index.row(), index.column(), self.rootItem.index_of(parent_item))151 mime_data = QMimeData()152 mime_data.setText(data)153 return mime_data154 def dropMimeData(self, mimedata, action, row, column, parentIndex):155 if action == Qt.IgnoreAction:156 return True157 data_str = str(mimedata.text())158 indexes = list(reversed(data_str.split("/")[:-1]))159 drag_nodes = []160 # Ensure we only drop groups or files161 contains_groups = False162 contains_files = False163 for index in indexes:164 row, column, parent = map(int, index.split(","))165 if parent == -1:166 parent = self.rootItem167 else:168 parent = self.rootItem.child(parent)169 node = parent.child(row)170 try:171 if node.is_group:172 contains_groups = True173 else:174 contains_files = True175 except AttributeError:176 logger.error("Could not perform drop for index {}".format(index))177 continue178 if contains_files and contains_groups:179 QMessageBox.information(QWidget(), self.tr("Drag not supported"),180 self.tr("You can only drag/drop groups or protocols, no mixtures of both."))181 return False182 drag_nodes.append(node)183 drop_node = self.getItem(parentIndex)184 if drop_node == self.rootItem:185 # Append to Last Group when dropped on root186 try:187 drop_node = self.rootItem.children[-1]188 except IndexError:189 return False190 if not drop_node.is_group:191 parent_node = drop_node.parent()192 dropped_on_group = False193 else:194 parent_node = drop_node195 dropped_on_group = True196 if parent_node is None:197 return False198 if dropped_on_group and contains_groups:199 parent_node = drop_node.parent()200 pos = parent_node.index_of(drop_node)201 parent_node.bringChildsToIndex(pos, drag_nodes)202 elif dropped_on_group:203 if parent_node.containsChilds(drag_nodes):204 # "Nodes on parent folder Dropped"205 parent_node.bringChildsToFront(drag_nodes)206 else:207 # "Nodes on distinct folder dropped"208 for dragNode in drag_nodes:209 parent_node.appendChild(dragNode)210 self.proto_to_group_added.emit(self.rootItem.index_of(parent_node))211 else:212 # Dropped on file213 if contains_groups:214 # Cant drop groups on files215 return False216 elif parent_node.containsChilds(drag_nodes) and drop_node in parent_node.children:217 # "Nodes on node in parent folder dropped"218 pos = parent_node.index_of(drop_node)219 parent_node.bringChildsToIndex(pos, drag_nodes)220 elif parent_node.containsChilds(drag_nodes):221 parent_node.bringChildsToFront(drag_nodes)222 else:223 # "Nodes on node in distinct folder dropped"224 pos = parent_node.index_of(drop_node)225 for dragNode in drag_nodes:226 dragNode.setParent(parent_node)227 parent_node.insertChild(pos, dragNode)228 self.proto_to_group_added.emit(self.rootItem.index_of(parent_node))229 self.item_dropped.emit()230 return True231 def insertRow(self, row, parent=None, *args, **kwargs):232 return self.insertRows(row, 1, parent)233 def insertRows(self, row, count, parent=None, *args, **kwargs):234 self.beginInsertRows(parent, row, (row + (count - 1)))235 self.endInsertRows()236 return True237 def removeRow(self, row, parentIndex=None, *args, **kwargs):238 return self.removeRows(row, 1, parentIndex)239 def removeRows(self, row, count, parentIndex=None, *args, **kwargs):240 self.beginRemoveRows(parentIndex, row, row)241 node = self.getItem(parentIndex)242 node.removeAtIndex(row)243 self.endRemoveRows()244 return True245 def addGroup(self, name="New group"):246 self.rootItem.addGroup(name)247 child_nr = self.rootItem.childCount() - 1248 self.group_added.emit(self.createIndex(child_nr, 0, self.rootItem.child(child_nr)))249 def delete_group(self, group_item: ProtocolTreeItem):250 if self.rootItem.childCount() == 1:251 QMessageBox.critical(self.controller, self.tr("Group not deletable"),252 self.tr(253 "You can't delete the last group. Think about the children, they would be homeless!"))254 return255 group_id = self.rootItem.index_of(group_item)256 if group_id == 0:257 new_group_index = 1258 else:259 new_group_index = group_id - 1260 new_group = self.rootItem.children[new_group_index]261 for i in reversed(range(group_item.childCount())):262 new_group.appendChild(group_item.children[i])263 self.removeRow(group_id, QModelIndex())264 self.group_deleted.emit(group_id, new_group_index)265 def move_to_group(self, items, new_group_id: int):266 """267 :type items: list of ProtocolTreeItem268 """269 group = self.rootItem.child(new_group_id)270 for item in items:271 group.appendChild(item)272 self.controller.refresh()273 def sort_group(self, sortgroup_id):274 self.blockSignals(True)275 self.rootItem.child(sortgroup_id).sortChilds()276 self.controller.refresh()277 self.blockSignals(False)278 def set_copy_mode(self, use_copy: bool):279 """280 Set all protocols in copy mode. They will return a copy of their protocol.281 This is used for writable mode in CFC.282 :param use_copy:283 :return:284 """285 for group in self.rootItem.children:286 for proto in group.children:...

Full Screen

Full Screen

tree.py

Source:tree.py Github

copy

Full Screen

1from .table import Columns2from dict import Dict3from PySide2.QtCore import QModelIndex, Qt, QAbstractItemModel4class Item():5 def __init__(self, data, kwchildren='children', tree=None):6 self.parent = None7 self.children = list()8 self.tree = tree9 if data is not None and isinstance(data, Dict):10 if kwchildren in data:11 for child in data[kwchildren]:12 child = Item(child, kwchildren, tree)13 child.parent = self14 self.children.append(child)15 self._data = data16 @property17 def data(self):18 return self._data19 @data.setter20 def data(self, data):21 self._data = data22 def appendChild(self, child):23 if not isinstance(child, Item):24 child = Item(child, self.tree.kwchildren, self.tree)25 child.parent = self26 self.children.append(child)27 def childCount(self):28 return len(self.children)29 def columnCount(self):30 if self.tree is not None and isinstance(self.tree, Tree):31 return len(self.tree.columns)32 else:33 return 034 def child(self, index):35 if len(self.children) > index:36 return self.children[index]37 else:38 return None39 def row(self):40 if self.parent is not None:41 return self.parent.children.index(self)42 else:43 return 044class Tree(QAbstractItemModel):45 def __init__(self):46 QAbstractItemModel.__init__(self)47 self.columns = Columns(self)48 self.classitem = Item49 self._rootitem = None50 self.kwchildren = 'children'51 def rowCount(self, parent):52 if not parent.isValid():53 parentItem = self.rootitem54 else:55 parentItem = parent.internalPointer()56 if parentItem is not None:57 return parentItem.childCount()58 else:59 return 060 def columnCount(self, parent=None):61 return len(self.columns)62 @property63 def rootitem(self):64 return self._rootitem65 @rootitem.setter66 def rootitem(self, rootitem):67 if not isinstance(rootitem, self.classitem):68 rootitem = self.classitem(rootitem, self.kwchildren, tree=self)69 self._rootitem = rootitem70 self.notify_update_all()71 def notify_update_all(self):72 self.modelReset.emit()73 @property74 def datasoure(self):75 if self.rootitem is not None and isinstance(self.rootitem, self.classitem):76 return self.rootitem.data.children77 else:78 return None79 def index(self, row, column, parent):80 if not parent.isValid():81 parentItem = self.rootitem82 else:83 parentItem = parent.internalPointer()84 childItem = parentItem.child(row)85 if childItem:86 return self.createIndex(row, column, childItem)87 else:88 return QModelIndex()89 def parent(self, index):90 if not index.isValid():91 return QModelIndex()92 childItem = index.internalPointer()93 parentItem = childItem.parent94 if parentItem == self.rootitem:95 return QModelIndex()96 else:97 return self.createIndex(parentItem.row(), 0, parentItem)98 def headerData(self, section, orientation, role=Qt.DisplayRole):99 if orientation == Qt.Horizontal and role == Qt.DisplayRole:100 column = self.columns[section]101 if column.name is not None:102 return column.name103 else:104 return column.fieldname105 def data(self, index, role=Qt.DisplayRole):106 if not index.isValid() or role != Qt.DisplayRole:107 return None108 item = index.internalPointer()109 column = self.columns[index.column()]110 data = column.get_data(item.data)111 if data is not None:...

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