def rowCount(self, index=QtCore.QModelIndex()): """ The total number of rows, or number of children for the given index. :param index: Overrides should return 0 for valid indices (if no children exist) or the number of the total *rows* (including column labels) exposed by the model. """ return 0 if index.isValid() else self.numrows + self._nheaders[0]
def insert(self, n, data): """ Insert a row into table. @param int n: insert before nth element @param data: row to insert """ with self.lock: if 0 <= n <= len(self.storage): self.beginInsertRows(QtCore.QModelIndex(), n, n) self.storage.insert(n, data) self.endInsertRows()
def columnCount(self, index=QtCore.QModelIndex()): """The number of columns of the given model index. Overridden to return 0 for valid indices because they have no children; otherwise return the total number of *columns* exposed by the model. :param index: the model index being inspected. """ return 0 if index.isValid() else self.numcols
def __init__(self, leaf, parent=None): """Create the model. """ # The model data source (a PyTables/HDF5 leaf) and its access buffer self.leaf = leaf self.rbuffer = buffer.Buffer(leaf) self.leaf_numrows = self.rbuffer.total_nrows() self.numrows = min(self.leaf_numrows, CHUNK_SIZE) self.start = 0 # The dataset number of columns doesn't use to be large so, we don't # need set a maximum as we did with rows. The whole set of columns # are displayed if isinstance(leaf, tables.Table): # Leaf is a PyTables table self.numcols = len(leaf.colnames) elif isinstance(leaf, tables.EArray): self.numcols = 1 else: # Leaf is some kind of PyTables array shape = leaf.shape if len(shape) > 1: # The leaf will be displayed as a bidimensional matrix self.numcols = shape[1] else: # The leaf will be displayed as a column vector self.numcols = 1 # # Choose a format for cells # self.formatContent = vitables.utils.formatArrayContent # Time series (if they are found) are formatted transparently # via the time_series.py plugin if not isinstance(leaf, tables.Table): # Leaf is some kind of PyTables array atom_type = leaf.atom.type if atom_type == 'object': self.formatContent = vitables.utils.formatObjectContent elif atom_type in ('vlstring', 'vlunicode'): self.formatContent = vitables.utils.formatStringContent # Track selected cell self.selected_cell = {'index': QtCore.QModelIndex(), 'buffer_start': 0} # Populate the model with the first chunk of data self.loadData(0, self.numrows) super(LeafModel, self).__init__(parent)
def check_node_open(self, filepath, nodepath): """Open file get access to a node and read all cells.""" try: leaf_model = get_leaf_model_with_assert(self, filepath, nodepath) for row in range(leaf_model.rowCount()): for column in range(leaf_model.columnCount()): cell_index = leaf_model.index(row, column, QtCore.QModelIndex()) cell_data = leaf_model.data(cell_index) finally: self.vtapp.fileClose()
def get_sequence(self): """ Returns a (deep)copy of the PulseSequence instance serving as model for this editor. @return: object, an instance of PulseSequence """ data_container = self.model().data(QtCore.QModelIndex(), self.model().sequenceRole) sequence_copy = copy.deepcopy(data_container) sequence_copy.name = '' sequence_copy.refresh_parameters() return sequence_copy
def set_block_ensemble(self, block_ensemble): """ @param block_ensemble: @return: """ if not isinstance(block_ensemble, PulseBlockEnsemble): return False self.beginResetModel() self.setData(QtCore.QModelIndex(), block_ensemble, self.blockEnsembleRole) self.endResetModel() return True
def get_block(self): """ Returns a (deep)copy of the PulseBlock instance serving as model for this editor. @return: PulseBlock, an instance of PulseBlock """ block_copy = copy.deepcopy(self.model().data( QtCore.QModelIndex(), self.model().pulseBlockRole)) block_copy.name = '' block_copy.refresh_parameters() return block_copy
def set_pulse_sequence(self, pulse_sequence): """ @param pulse_sequence: @return: """ if not isinstance(pulse_sequence, PulseSequence): return False self.beginResetModel() self.setData(QtCore.QModelIndex(), pulse_sequence, self.sequenceRole) self.endResetModel() return True
def cleanupThread(self, name): """Remove thread from thread list. @param str name: unique thread name """ if name in self._threads and not self._threads[name].thread.isRunning(): logger.debug('Cleaning up thread {0}.'.format(name)) with self.lock: row = self.getItemNumberByKey(name) self.beginRemoveRows(QtCore.QModelIndex(), row, row) self._threads.pop(name) self.endRemoveRows()
def append(self, data): """ Add a task to the end of the storage list and listen to its signals. @param object data: PrePostTask or InterruptableTask to add to list. """ with self.lock: n = len(self.storage) self.beginInsertRows(QtCore.QModelIndex(), n, n) self.storage.append(data) self.endInsertRows() self.storage[-1]['object'].sigStateChanged.connect( lambda x: self.dataChanged.emit(self.index(n, 1), self.index(n, 1)))
def get_index(model, node_name, start_index=None): """Return index of the node with the given name or None.""" start_index = start_index if start_index else QtCore.QModelIndex() for c in range(model.columnCount(start_index)): for r in range(model.rowCount(start_index)): index = model.index(r, c, start_index) if index.data(QtCore.Qt.DisplayRole) == node_name: return index child_search_result = get_index(model, node_name, index) if child_search_result: return child_search_result return None
def syncTreeView(self): """ If the view is activated select its leaf in the tree of databases view. """ if self.vtgui.editing_dlg is not None: self.vtgui.editing_dlg = None return # Locate the tree view leaf tied to this data sheet. Persistent # indices are used to get direct access to the leaf so we don't # have to walk the tree self.vtgui.dbs_tree_view.setCurrentIndex( QtCore.QModelIndex(self.pindex))
def removeRows(self, row, count, parent=QtCore.QModelIndex()): """ Remove rows (log entries) from model. @param int row: from which row on to remove rows @param int count: how many rows to remove @param QModelIndex parent: parent model index @return bool: True if removal succeeded, False otherwise """ self.beginRemoveRows(parent, row, row + count - 1) self.entries[row:row + count] = [] self.endRemoveRows() return True
def columnCount(self, parent=QtCore.QModelIndex()): if (isinstance(self.datatable, (list, tuple)) and len(self.datatable) > 0): if isinstance(self.datatable[0], (list, tuple)): return len(self.datatable[0]) else: return 1 elif np and isinstance(self.datatable, np.ndarray): return int(self.datatable.shape[1]) else: return 0
def requestRefresh(self): if self._dataSource and (reload or self._dataSource.needToRefresh): self._dataSource.setNeedToRefresh(False) self.dataAboutToBeRefreshed.emit() itemList = self._dataSource.fetchItems(QtCore.QModelIndex()) self.setItems(itemList) self.dataRefreshed.emit() return True
def updateTreeFromData(self, parent_index=None): """Update tree of expanded nodes from hdf5 data. This function should be used if the structure of a file was updated through pytables functions. It is better to use model functions but they need to be better documented and expanded to be usefull. This function is a temporary fix. """ parent_index = parent_index if parent_index else QtCore.QModelIndex() self.lazyAddChildren(parent_index) for index in self.indexChildren(parent_index): self.updateTreeFromData(index)
def pop(self, n): """ Remove nth row from table. @param int n: index of row to remove @return data: removed row """ with self.lock: if 0 <= n < len(self.storage): self.beginRemoveRows(QtCore.QModelIndex(), n, n) ret = self.storage.pop(n) self.endRemoveRows() return ret
def insertRows(self, position, rows, parent=QtCore.QModelIndex()): """insert rows from starting position and number given by rows""" parentNode = self.getNode(parent) self.beginInsertRows(parent, position, position + rows - 1) for row in range(rows): childCount = parentNode.childCount() childNode = Node("untitled" + str(childCount)) success = parentNode.insertChild(position, childNode) self.endInsertRows() return success
def columnCount(self): """ Tests self.model's implementation of QtCore.QAbstractItemModel::columnCount() and hasChildren() """ # check top row topidx = self.model.index(0, 0, QtCore.QModelIndex()) assert (self.model.columnCount(topidx) >= 0) # check a column count where parent is valid childidx = self.model.index(0, 0, topidx) if childidx.isValid(): assert (self.model.columnCount(childidx) >= 0)
def index(self, row, column, parent): """ Make QModelIndex from row and column number. @param row int: row number @param column int: column number @param parent QAbstractModel: model parent @return QModelIndex: index for item at position """ if not self.hasIndex(row, column, parent): return QtCore.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 del_keypoint(self, idx: int) -> None: """ Delete a keypoint by index :param idx: :return: """ # Refuse to delete existing keypoints if not self.keypoints[idx].is_new: return self.combo_adapter.beginRemoveRows(QtCore.QModelIndex(), idx, idx) del self.__keypoints[idx] self.combo_adapter.endRemoveRows() self.change()
def add_keypoint(self) -> int: """ Adds a new keypoint. Returns the index of the new keypoint :return: """ idx = len(self.__keypoints) self.combo_adapter.beginInsertRows(QtCore.QModelIndex(), idx, idx) self.__keypoints.append(AlignKeypoint()) self.combo_adapter.endInsertRows() self.change() return idx
def move_artist(self, artist, row): """Move an artist before the entry in row Row could be the end of the list (-> put it at the end) """ if len(self.artists) < 2: # can't rearrange lenght 0 or 1 list return try: loc = self.artists.index(artist) except ValueError: return dest = row if not self.beginMoveRows(QtCore.QModelIndex(), loc, loc, QtCore.QModelIndex(), dest): return if dest >= loc: row -= 1 self.artists.pop(loc) self.artists.insert(row, artist) self._update_zorder() self.endMoveRows()
def pop(self, key): """ Remove key from dictionary. @param key: dict key to remove @return value: value removed from dict """ with self.lock: if key in self.storage: row = self.getNumberByKey(key) self.beginRemoveRows(QtCore.QModelIndex(), row, row) ret = self.storage.pop(key) self.endRemoveRows() return ret
def add(self, key, data): """ Append key and data to dictionary, update model. @param key: dict key @param data: dict data @return key: dict key """ with self.lock: if key in self.storage: return None row = len(self.storage) self.beginInsertRows(QtCore.QModelIndex(), row, row) self.storage[key] = data self.endInsertRows() return key
def insertRows(self, row, count, parent=QtCore.QModelIndex()): """ Insert empty rows (log entries) into the model. @param int row: before which row to insert new rows @param int count: how many rows to insert @param QModelIndex parent: patent model index @return bool: True if insertion succeeded, False otherwise """ self.beginInsertRows(parent, row, row + count - 1) insertion = list() for ii in range(count): insertion.append([None, None, None, None]) self.entries[row:row] = insertion self.endInsertRows() return True
def set_pulse_block(self, pulse_block): """ @param pulse_block: @return: """ if not isinstance(pulse_block, PulseBlock): return False elif pulse_block.channel_set != self.activation_config: return False self.beginResetModel() self.setData(QtCore.QModelIndex(), pulse_block, self.pulseBlockRole) self._col_widths = self._get_column_widths() self._notify_column_width() self.endResetModel() return True
def Tree_open_parents(self, item_index): try: if not (item_index.isValid()): return flag = True empty = QtCore.QModelIndex() parent = item_index while flag: parent = parent.parent() if parent != empty: self.ui.Tree.expand(parent) else: flag = False break except Exception as e: self.status_sig.emit(str(e))
def find_identifier_root(model, identifier): """Find the identifier root group in the model. Identifier is a string, root group is found by matching item name to identifier beggining. The second return argument contains path to to identifier node relative to root. """ root_index = QtCore.QModelIndex() for row in range(model.rowCount(root_index)): index = model.index(row, 0, root_index) name = model.data(index, QtCore.Qt.DisplayRole) if identifier.startswith(name): return (model.nodeFromIndex(index).node, identifier[len(name) + 1:]) return None, None