我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用PyQt4.QtCore.QModelIndex()。
def add_document (self, document): """Add document to model.""" if not document: return False assert isinstance(document, unicode) while document in self.documents: row = self.documents.index(document) self.beginRemoveRows(QtCore.QModelIndex(), row, row) del self.documents[row] self.endRemoveRows() while len(self.documents) >= self.maxentries: row = len(self.documents) - 1 self.beginRemoveRows(QtCore.QModelIndex(), row, row) del self.documents[row] self.endRemoveRows() self.beginInsertRows(QtCore.QModelIndex(), 0, 0) self.documents.insert(0, document) self.endInsertRows() return True
def refresh_protocols(self): prev_proto_count = len(self.protocols) self.protocols = self.remote_proto.get_protocols() new_proto_count = len(self.protocols) if new_proto_count > prev_proto_count: num_new_rows = new_proto_count - prev_proto_count self.insertRows(prev_proto_count, num_new_rows, QtCore.QModelIndex(), "") if new_proto_count < prev_proto_count: num_deleted_rows = prev_proto_count - new_proto_count del_start = prev_proto_count - num_deleted_rows if del_start != 0: del_start = del_start - 1 self.removeRows(del_start, num_deleted_rows-1, QtCore.QModelIndex()) self.emit_data_changed()
def traverseChildrenAndFindShape(self, item_model, item_index, shape): """ This method is used by the findLayerItemIndexFromShape() and findEntityItemIndexFromShape() function in order to find a reference from a layer. It traverses the QT model and compares each item data with the shape passed as parameter. When found, the reference is returned options @param item_model: the treeView model (used to store the data, see QT docs) @param item_index: the initial model index (QModelIndex) in the tree (all children of this index are scanned) @param shape: the real shape (ShapeClass instance) @return: the found item index """ for i in range(item_model.rowCount(item_index)): sub_item_index = item_model.index(i, 0, item_index) if isValid(sub_item_index.data(SHAPE_OBJECT)): real_item = toPyObject(sub_item_index.data(SHAPE_OBJECT)).shapeobj if shape == real_item: return sub_item_index if item_model.hasChildren(sub_item_index): found_item_index = self.traverseChildrenAndFindShape(item_model, sub_item_index, shape) if found_item_index: return found_item_index
def traverseChildrenAndEnableDisable(self, item_model, item_index, checked_state): """ This method is used internally to check/uncheck all children of a given entity (eg to enable all shapes of a given layer when the user has enabled a layer) options @param item_model: the treeView model (used to store the data, see QT docs) @param item_index: the initial model index (QModelIndex) in the tree (all children of this index are scanned) @param checked_state: the state of the checkbox """ for i in range(item_model.rowCount(item_index)): sub_item_index = item_model.index(i, 0, item_index) if item_model.hasChildren(sub_item_index): self.traverseChildrenAndEnableDisable(item_model, sub_item_index, checked_state) item = item_model.itemFromIndex(sub_item_index) if item and item.isEnabled(): # FIXME when parent was partially checked and a child cannot be checked self.updateCheckboxOfItem(item, checked_state)
def ecuSel(self, index): if index.parent() == core.QModelIndex(): return item = self.list.model().itemData(self.list.model().index(index.row(), 0, index.parent())) selected = unicode(item[0].toPyObject().toUtf8(), encoding="UTF-8") target = self.ecuscan.ecu_database.getTarget(selected) name = selected if target: self.ecuscan.addTarget(target) if target.addr in self.ecuscan.ecu_database.addr_group_mapping: group = self.ecuscan.ecu_database.addr_group_mapping[target.addr] else: group = "Unknown" name = "[ " + group + " ] " + name if selected: if name not in options.main_window.ecunamemap: options.main_window.ecunamemap[name] = selected self.treeview_ecu.addItem(name)
def setValue(self, value, undo=False): if not self._actualValue == value: if undo: self.emit(QtCore.SIGNAL("valueChanged"), copy.deepcopy( self._actualValue), copy.deepcopy(value)) self._actualValue = copy.deepcopy(value) rows = len(value) if (self._format == "2D") and (rows > 0): columns = len(value[0]) else: columns = 1 self._model = QtGui.QStandardItemModel(rows, columns) for row in range(rows): for column in range(columns): index = self._model.index(row, column, QtCore.QModelIndex()) if (self._format == "1D"): self._model.setData(index, QtCore.QVariant(value[row])) if (self._format == "2D"): self._model.setData( index, QtCore.QVariant(value[row][column])) self._tableView.setModel(self._model)
def rowCount (self, parent=QtCore.QModelIndex()): """Return number of documents.""" return len(self.documents)
def index (self, row, column=0, parent=QtCore.QModelIndex()): """Return index of document in given row.""" return self.createIndex(row, column)
def rowCount (self, parent=QtCore.QModelIndex()): """Return number of URL items.""" return len(self.urls)
def columnCount (self, parent=QtCore.QModelIndex()): """Return number of header columns.""" return len(Headers)
def index (self, row, column, parent=QtCore.QModelIndex()): """Return index of URL item in given row and column.""" return self.createIndex(row, column)
def log_url (self, url_data): """Add URL data to tree model.""" row = self.rowCount() self.beginInsertRows(QtCore.QModelIndex(), row, row) self.urls.append(UrlItem(url_data)) self.endInsertRows() return True
def _modify_qtree(self, tree, items): for i in items: tree.setRowHidden(i, QModelIndex(), True)
def insertRows(self, position, numrows, index, event): print "Inserting row @ %s with numrows=%s index=%s"%(str(position),str(numrows),str(index)) self.beginInsertRows(QtCore.QModelIndex(), position, position+numrows-1) self.requests.append(event) self.endInsertRows()
def select_row(self, row): index = self.rulemod.index(row, 0, QtCore.QModelIndex()) rules = self.main.listrules # Get a selection model model = rules.selectionModel() model.select(index, QtGui.QItemSelectionModel.Select) model.setCurrentIndex(index, QtGui.QItemSelectionModel.NoUpdate) self.handle_ruleactivated(index)
def insertRows(self, position, numrows, index, event): self.beginInsertRows(QtCore.QModelIndex(), position, position+numrows-1) self.endInsertRows()
def columnCount(self, parent=QModelIndex()): return 2
def rowCount(self, parent=QModelIndex()): if self.node is None: return 0 parent_item = None if not parent.isValid(): parent_item = self.node else: parent_item = parent.internalPointer() return len(parent_item.children)
def index(self, row, column, parent=QModelIndex()): parent_item = None if not parent.isValid(): parent_item = self.node else: parent_item = parent.internalPointer() return self.createIndex(row, column, parent_item.children[row])
def parent(self, index): item = index.internalPointer() if item.parent is None: # root case return QModelIndex() return self.createIndex(item.parent.row, 0, item.parent)
def parent(self,index): if not index.isValid(): return QtCore.QModelIndex() treeNode = index.internalPointer() # cannot fail assert treeNode.parent is not None if treeNode.parent is None: pass # TODO FIXME XXX but Qt models *are* messy! return self.createIndex(treeNode.parent.row,0,treeNode.parent)
def updateExportOrder(self, includeDisableds=False): """ Update the layers_list order to reflect the TreeView order. This function must be called before generating the GCode (export function). Export will be performed in the order of the structure self.LayerContents of the main. Each layer contains some shapes, and the export order of the shapes is set by populating the exp_order[] list with the shapes reference number for each layer (eg exp_order = [5, 3, 2, 4, 0, 1] for layer 0, exp_order = [5, 3, 7] for layer 1, ...) options """ i = self.layer_item_model.rowCount(QtCore.QModelIndex()) while i > 0: i -= 1 layer_item_index = self.layer_item_model.index(i, 0) if isValid(layer_item_index.data(LAYER_OBJECT)): real_layer = toPyObject(layer_item_index.data(LAYER_OBJECT)) self.layers_list.remove(real_layer) # Remove the layer from its original position self.layers_list.insert(0, real_layer) # and insert it at the beginning of the layer's list real_layer.exp_order = [] # Clear the current export order real_layer.exp_order_complete = [] # Clear the current export order # Assign the export order for the shapes of the layer "real_layer" for j in range(self.layer_item_model.rowCount(layer_item_index)): shape_item_index = self.layer_item_model.index(j, 0, layer_item_index) real_shape = None if isValid(shape_item_index.data(SHAPE_OBJECT)): real_shape = toPyObject(shape_item_index.data(SHAPE_OBJECT)).shapeobj if not real_shape.isDisabled() or includeDisableds: real_layer.exp_order.append(real_shape.nr) # Create the export order list with the real and unique shapes numbers (eg [25, 22, 30, 4, 1, 5]) if isValid(shape_item_index.data(CUSTOM_GCODE_OBJECT)): real_shape = toPyObject(shape_item_index.data(CUSTOM_GCODE_OBJECT)) if real_shape and (not real_shape.isDisabled() or includeDisableds): real_layer.exp_order_complete.append(real_layer.shapes.index(real_shape)) # Create the export order list with the shapes & custom gcode numbers (eg [5, 3, 2, 4, 0, 1])
def updateTreeViewOrder(self): """ Update the Layer TreeView order according to the exp_order list of each layer. This function should be called after running the TSP path otimizer """ i = self.layer_item_model.rowCount(QtCore.QModelIndex()) while i > 0: i -= 1 layer_item_index = self.layer_item_model.index(i, 0) layer_item = self.layer_item_model.itemFromIndex(layer_item_index) if isValid(layer_item_index.data(LAYER_OBJECT)): real_layer = toPyObject(layer_item_index.data(LAYER_OBJECT)) # for shape_nr in real_layer.exp_order[::-1]: # reverse order and prepend if we want to insert optimized shape before fixed shapes for shape_nr in real_layer.exp_order: for j in range(self.layer_item_model.rowCount(layer_item_index)): shape_item_index = self.layer_item_model.index(j, 0, layer_item_index) if isValid(shape_item_index.data(SHAPE_OBJECT)): real_shape = toPyObject(shape_item_index.data(SHAPE_OBJECT)).shapeobj if real_shape and real_shape.nr == shape_nr and (real_shape.send_to_TSP or g.config.vars.Route_Optimisation['TSP_shape_order'] == 'CONSTRAIN_ORDER_ONLY'): # Shape number "shape_nr" found in the treeView and Shape is movable => moving it to its new position item_to_be_moved = layer_item.takeRow(j) layer_item.appendRow(item_to_be_moved) break
def findLayerItemIndexFromShape(self, shape): """ Find internal layers treeView reference (item index) matching a "real" shape (ie a ShapeClass instance) options @param shape: the real shape (ShapeClass instance) @return: the found item index (can be None) """ return self.traverseChildrenAndFindShape(self.layer_item_model, QtCore.QModelIndex(), shape)
def findEntityItemIndexFromShape(self, shape): """ Find internal entities treeView reference (item index) matching a "real" shape (ie a ShapeClass instance) options @param shape: the real shape (ShapeClass instance) @return: the found item index (can be None) """ return self.traverseChildrenAndFindShape(self.entity_item_model, QtCore.QModelIndex(), shape)
def rowCount(self, index=QModelIndex()): return self.df.shape[0]
def columnCount(self, index=QModelIndex()): return self.df.shape[1]
def index(self, row, column, parent): if not self.hasIndex(row, column, parent): return QtCore.QModelIndex() if not parent.isValid(): parent_item = self.rootItem else: parent_item = parent.internalPointer() childItem = parent_item.child(row) if childItem: return self.createIndex(row, column, childItem) else: return QtCore.QModelIndex()
def parent(self, index): if not index.isValid(): return QtCore.QModelIndex() childItem = index.internalPointer() if not childItem: return QtCore.QModelIndex() parent_item = childItem.parent() if parent_item == self.rootItem: return QtCore.QModelIndex() return self.createIndex(parent_item.row(), 0, parent_item)
def rowCount(self, parent=QtCore.QModelIndex()): if parent.column() > 0: return 0 if not parent.isValid(): p_item = self.rootItem else: p_item = parent.internalPointer() return p_item.childCount()
def setWaveSource(self, item, force=False): if item.row() == -1 or item.column() == -1: self.wave_source_view.clear() self.wave_panel.setEnabled(False) self.bal_panel.setVisible(False) return stream = item.data(streamRole).toPyObject() if isinstance(item, QtCore.QModelIndex): self.currentStream = self.wave_model.itemFromIndex(item) else: self.currentStream = item self.gain_spin.setValue(item.data(gainRole).toPyObject()) if stream.getnchannels() == 1: self.bal_widget.setEnabled(False) self.bal_panel.setVisible(False) else: self.bal_widget.setEnabled(True) self.bal_panel.setVisible(self.bal_panel_visible) balance_active = item.data(balanceActiveRole).toPyObject() if balance_active: self.bal_chk.setChecked(True) self.bal_combo.setCurrentIndex(item.data(balanceModeRole).toPyObject()) self.bal_slider.setValue(item.data(balanceValueRole).toPyObject()) else: self.bal_chk.setChecked(False) self.left_spin.setValue(item.data(balanceLeftRole).toPyObject()) self.right_spin.setValue(item.data(balanceRightRole).toPyObject()) self.wave_source_view.draw_wave(stream, force) self.wave_source_view.current_source = item.data(QtCore.Qt.DisplayRole).toPyObject()
def add(self, children): children = children if hasattr(children, '__iter__') else [children] i = len(self) self.model.beginInsertRows(self.index, len(self), len(self) + len(children) - 1) self.__children.extend(children) self.model.endInsertRows() self.model.dataChanged.emit(QtCore.QModelIndex(), QtCore.QModelIndex()) return i
def index(self): """Get the model index of this tree item""" # root does have default model index if self.__parent is None: return QtCore.QModelIndex() else: return self.model.index(self.parent.row(self), 0, self.parent.index)
def parent(self, index): """Returns the parent of the model item with the given index. If the item has no parent, an invalid QModelIndex is returned.""" item = index.internalPointer() if index.isValid() else self.root if item is self.root: return QtCore.QModelIndex() return item.parent.index
def moveSelection(self, parent, position): # save the selected items if parent.type == None: return selection = [QtCore.QPersistentModelIndex(i) for i in self.selectedIndexes()] parent_index = self.indexFromItem(parent) if parent_index in selection: return False # save the drop location in case it gets moved target = self.model().index(position, 0, parent_index).row() if target < 0: target = position # remove the selected items taken = [] for index in reversed(selection): item = self.itemFromIndex(QtCore.QModelIndex(index)) if item is None or item.parent() is None: taken.append(self.takeTopLevelItem(index.row())) else: taken.append(item.parent().takeChild(index.row())) # insert the selected items at their new positions while taken: if position == -1: # append the items if position not specified if parent_index.isValid(): parent.insertChild( parent.childCount(), taken.pop(0)) else: self.insertTopLevelItem( self.topLevelItemCount(), taken.pop(0)) else: # insert the items at the specified position if parent_index.isValid(): parent.insertChild(min(target, parent.childCount()), taken.pop(0)) else: self.insertTopLevelItem(min(target, self.topLevelItemCount()), taken.pop(0)) return True
def rowCount(self, parent=QModelIndex()): return len(self._docs)
def clear(self): if self._docs == []: return self.beginRemoveRows(QModelIndex(), 0, self.rowCount() - 1) self._docs = [] self.endRemoveRows()
def _runQuery(self, querystr): self.clear() docs = self.db.get_docs_from_query( str(querystr), start=0, end=500, category=self._category) self.beginInsertRows(QModelIndex(), 0, len(docs) - 1) self._docs = docs self.endInsertRows() # install/remove interface (for qml)
def rowCount(self, parent=QModelIndex()): return len(self._categories)
def rowCount(self, parent=QModelIndex()): return len(self._reviews)
def _on_reviews_ready_callback(self, loader, reviews): self.beginInsertRows(QModelIndex(), self.rowCount(), # first self.rowCount() + len(reviews) - 1) # last self._reviews += reviews self.endInsertRows() # getReviews interface (for qml)
def clear(self): self.beginRemoveRows(QModelIndex(), 0, self.rowCount() - 1) self._reviews = [] self.endRemoveRows()
def __init__(self, parent=None): super(SimpleTreeView, self).__init__(parent) self.setSelectionBehavior(QtGui.QTreeView.SelectItems) self.setUniformRowHeights(True) # self.connect(self, QtCore.SIGNAL("activated(QModelIndex)"), self.activated) self.connect(self, QtCore.SIGNAL("expanded(QModelIndex)"), self.expanded) self.expanded()
def expanded(self): if not self.model() is None: for column in range(self.model().columnCount( QtCore.QModelIndex())): self.resizeColumnToContents(column)
def setValue(self, value): rows = len(value) columns = 2 self._model = QtGui.QStandardItemModel(rows, columns) for row in range(rows): for column in range(columns): index = self._model.index(row, column, QtCore.QModelIndex()) self._model.setData(index, QtCore.QVariant(value[row][column])) self._model.setHeaderData(0, Qt.Qt.Horizontal, Qt.QVariant("Name")) self._model.setHeaderData(1, Qt.Qt.Horizontal, Qt.QVariant("Axis")) self._tableView.setModel(self._model) self._tableView.horizontalHeader().setVisible(True) self._tableView.horizontalHeader().setStretchLastSection(True)