我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用PyQt5.QtCore.QModelIndex()。
def removeRows(self, row, count, index): if index.isValid(): return False if count <= 0: return False num_rows = self.rowCount(QtCore.QModelIndex()) self.beginRemoveRows(QtCore.QModelIndex(), row, row + count - 1) for i in range(count, 0, -1): self.nodes.pop(row - i + 1) self.endRemoveRows() if self.pendingRemoveRowsAfterDrop: ''' If we got here, it means this call to removeRows is the automatic 'cleanup' action after drag-n-drop performed by Qt ''' self.pendingRemoveRowsAfterDrop = False self.dragDropFinished.emit() return True
def delProject( self, project_name ): item = self.invisibleRootItem() row = 0 while True: child = item.child( row ) if child is None: # not found return if child.text() == project_name: break row += 1 self.removeRow( row, QtCore.QModelIndex() )
def log_tree(self, index: QtCore.QModelIndex): item = self.prj_tree.model().itemFromIndex(index) # type: QtWidgets.QListWidgetItem text = str(item.text()) return # if text.startswith('Flight:'): # self.log.debug("Clicked Flight object") # _, flight_id = text.split(' ') # flight = self.project.get_flight(flight_id) # type: prj.Flight # self.log.debug(flight) # grav_data = flight.gravity # # if grav_data is not None: # self.log.debug(grav_data.describe()) # else: # self.log.debug("No grav data") # # self.log.debug(text) # # self.log.debug(item.toolTip()) # print(dir(item)) ##### # Plot functions #####
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 parent(self, index): if not index.isValid(): return QtCore.QModelIndex() item = index.internalPointer() if not item: return QtCore.QModelIndex() pitem = item.parent if pitem == self.rootnode: return QtCore.QModelIndex() if pitem is None: return QtCore.QModelIndex() return self.createIndex(pitem.row(), 0, pitem)
def index(self, row, column, parentIndex=None): """Return the index of the item in the model specified by the given row, column, and parent index. """ if parentIndex is None or not parentIndex.isValid(): parentNode = self.rootNode else: parentNode = self.getNode(parentIndex) childNode = parentNode.child(row) if childNode: index = self.createIndex(row, column, childNode) else: index = QModelIndex() return index
def data(self, index: QModelIndex, role=None): row = index.row() if role == Qt.DisplayRole: if row == 0: return "not assigned" else: try: return self.participants[row-1].name + " ("+ self.participants[row-1].shortname + ")" except IndexError: return None elif role == Qt.CheckStateRole: if row == 0: return Qt.Checked if self.show_unassigned else Qt.Unchecked else: try: return Qt.Checked if self.participants[row-1].show else Qt.Unchecked except IndexError: return None
def delete_group(self, group_item: ProtocolTreeItem): if self.rootItem.childCount() == 1: QMessageBox.critical(self.controller, self.tr("Group not deletable"), self.tr( "You can't delete the last group. Think about the children, they would be homeless!")) return group_id = self.rootItem.index_of(group_item) if group_id == 0: new_group_index = 1 else: new_group_index = group_id - 1 new_group = self.rootItem.children[new_group_index] for i in reversed(range(group_item.childCount())): new_group.appendChild(group_item.children[i]) self.removeRow(group_id, QModelIndex()) self.group_deleted.emit(group_id, new_group_index)
def setData(self, index: QModelIndex, value, role=None): i = index.row() j = index.column() hex_chars = ("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f") if self.proto_view == 0 and value in ("0", "1"): l = list(self.data[i]) l[j] = value self.data[i] = ''.join(l) self.update() elif self.proto_view == 1 and value in hex_chars: l = list(self.data[i]) l[4*j : 4 * (j + 1)] = "{0:04b}".format(int(value, 16)) self.data[i] = ''.join(l) self.update() elif self.proto_view == 2 and len(value) == 1: l = list(self.data[i]) l[8*j : 8 * (j + 1)] = "{0:08b}".format(ord(value)) self.data[i] = ''.join(l) self.update() return True
def data(self, index: QModelIndex, role=Qt.DisplayRole): if not index.isValid(): return None if role == Qt.DisplayRole: i = index.row() j = index.column() rule = self.ruleset[i] assert isinstance(rule, Rule) if j == 0: return rule.start + 1 elif j == 1: return rule.end elif j == 2: return rule.value_type elif j == 3: return rule.operator_description elif j == 4: return rule.target_value
def setData(self, index: QModelIndex, value, role=None): if role == Qt.EditRole: i, j = index.row(), index.column() rule = self.ruleset[i] try: if j == 0: rule.start = int(value) - 1 elif j == 1: rule.end = int(value) if j == 2: rule.value_type = int(value) if j == 3: rule.operator_description = self.operator_descriptions[int(value)] if j == 4: rule.target_value = value except ValueError: return False return True
def data(self, index: QModelIndex, role=None): row = index.row() if role == Qt.DisplayRole: if row == 0: return "not assigned" else: try: return self.participants[row-1].name + " ("+ self.participants[row-1].shortname + ")" except IndexError: return None elif role == Qt.BackgroundColorRole: if row > 0: try: return constants.PARTICIPANT_COLORS[self.participants[row-1].color_index] except IndexError: return None elif role == Qt.TextColorRole: if row > 0: try: bgcolor = constants.PARTICIPANT_COLORS[self.participants[row-1].color_index] red, green, blue = bgcolor.red(), bgcolor.green(), bgcolor.blue() return QColor("black") if (red * 0.299 + green * 0.587 + blue * 0.114) > 186 else QColor("white") except IndexError: return None
def setData(self, index: QModelIndex, value, role=Qt.DisplayRole): i = index.row() j = index.column() if i >= len(self.participants): return False participant = self.participants[i] if j == 0: participant.name = value elif j == 1: participant.shortname = value elif j == 2: participant.color_index = int(value) elif j == 3: for other in self.participants: if other.relative_rssi == int(value): other.relative_rssi = participant.relative_rssi break participant.relative_rssi = int(value) self.participant_rssi_edited.emit() elif j == 4: participant.address_hex = value return True
def setData(self, index: QModelIndex, value, role: int = ...): try: int_val = int(value) except ValueError: return False i, j = index.row(), index.column() if i > len(self.checksum_label.data_ranges): return False data_range = self.checksum_label.data_ranges[i] if j == 0: converted_index = self.message.convert_index(int_val - 1, self.proto_view, 0, True)[0] if converted_index < data_range[1]: data_range[0] = converted_index elif j == 1: converted_index = self.message.convert_index(int_val, self.proto_view, 0, True)[0] if converted_index > data_range[0]: data_range[1] = converted_index return True
def rowCount(self, parent=QtCore.QModelIndex()): '''The number of rows under the given parent. When the parent is valid it means that rowCount is returning the number of children of parent. Args: parent (:obj:`QtCore.QModelIndex`, optional): Parent Returns: int: Number of rows ''' if None == self._data: return 0 return len(self._data)
def execute_mcu_code(self): idx = self.mcuFilesListView.currentIndex() assert isinstance(idx, QModelIndex) model = self.mcuFilesListView.model() assert isinstance(model, QStringListModel) file_name = model.data(idx, Qt.EditRole) self._connection.run_file(file_name)
def remove_file(self): idx = self.mcuFilesListView.currentIndex() assert isinstance(idx, QModelIndex) model = self.mcuFilesListView.model() assert isinstance(model, QStringListModel) file_name = model.data(idx, Qt.EditRole) try: self._connection.remove_file(file_name) except OperationError: QMessageBox().critical(self, "Operation failed", "Could not remove the file.", QMessageBox.Ok) return self.list_mcu_files()
def open_local_file(self, idx): assert isinstance(idx, QModelIndex) model = self.localFilesTreeView.model() assert isinstance(model, QFileSystemModel) if model.isDir(idx): return local_path = model.filePath(idx) remote_path = local_path.rsplit("/", 1)[1] if local_path.endswith(".py"): if Settings().external_editor_path: self.open_external_editor(local_path) else: with open(local_path) as f: text = "".join(f.readlines()) self.open_code_editor() self._code_editor.set_code(local_path, remote_path, text) else: QMessageBox.information(self, "Unknown file", "Files without .py ending won't open" " in editor, but can still be transferred.")
def mcu_file_selection_changed(self): idx = self.mcuFilesListView.currentIndex() assert isinstance(idx, QModelIndex) if idx.row() >= 0: self.executeButton.setEnabled(True) self.removeButton.setEnabled(True) self.transferToPcButton.setEnabled(True) else: self.executeButton.setEnabled(False) self.removeButton.setEnabled(False) self.transferToPcButton.setEnabled(False)
def read_mcu_file(self, idx): assert isinstance(idx, QModelIndex) model = self.mcuFilesListView.model() assert isinstance(model, QStringListModel) file_name = model.data(idx, Qt.EditRole) if not file_name.endswith(".py"): QMessageBox.information(self, "Unknown file", "Files without .py ending won't open" " in editor, but can still be transferred.") return progress_dlg = FileTransferDialog(FileTransferDialog.DOWNLOAD) progress_dlg.finished.connect(lambda: self.finished_read_mcu_file(file_name, progress_dlg.transfer)) progress_dlg.show() self._connection.read_file(file_name, progress_dlg.transfer)
def remove_preset(self): idx = self.presetsListView.currentIndex() assert isinstance(idx, QModelIndex) if idx.row() < 0: return Settings().wifi_presets.remove(Settings().wifi_presets[idx.row()]) self.update_preset_list()
def select_preset(self): idx = self.presetsListView.currentIndex() assert isinstance(idx, QModelIndex) if idx.row() < 0: return _, self.selected_ip, self.selected_port, self.selected_password = Settings().wifi_presets[idx.row()] self.accept()
def index(self, row, column, parent): if row < 0 or row >= len(self.nodes): return QtCore.QModelIndex() return self.createIndex(row, column)
def parent(self, index): return QtCore.QModelIndex()
def insertRows(self, row, count, index): if index.isValid(): return False if count <= 0: return False # inserting 'count' empty rows starting at 'row' self.beginInsertRows(QtCore.QModelIndex(), row, row + count - 1) for i in range(0, count): self.nodes.insert(row + i, '') self.endInsertRows() return True
def finaliseRebase_Bg( self, rc, stdout, stderr, row_to_select ): for line in stdout: self.log.info( line ) if len(stderr) == 0 and rc != 0: stderr = ['rebase failed rc=%d' % (rc,)] for line in stderr: if rc == 0: self.log.info( line ) else: self.log.error( line ) if rc != 0: dialog = wb_common_dialogs.WbErrorDialog( self.app, self, T_('Rebase failed'), '\n'.join( stderr ) ) dialog.exec_() return # reload the commit history to pick up the rebase changes yield self.app.switchToBackground options = self.reload_commit_log_options self.log_model.loadCommitLogForRepository( self.ui_component.deferedLogHistoryProgress(), self.git_project, options.getLimit(), options.getSince(), options.getUntil() ) yield self.app.switchToForeground self.log_table.resizeColumnToContents( self.log_model.col_date ) self.log_table.setCurrentIndex( self.log_model.index( row_to_select, 0, QtCore.QModelIndex() ) ) self.ui_component.progress.end() self.updateEnableStates() self.show() #------------------------------------------------------------
def indexListFromNameList( self, all_names ): if len(all_names) == 0: return [] model = self.sourceModel() all_indices = [] for row in range( self.rowCount( QtCore.QModelIndex() ) ): index = self.createIndex( row, 0 ) entry = model.data( index, QtCore.Qt.UserRole ) if entry.name in all_names: all_indices.append( index ) return all_indices
def append(self, item): self.beginInsertRows(QtCore.QModelIndex(), self.rowCount(), self.rowCount()) self._items[-1].append(item) self.endInsertRows()
def data(self, index, role=QtCore.QModelIndex()): key = self._role_to_key[role].decode("utf-8") item = self._items[-1][index.row()] return item.get(key)
def paint(self, painter: QPainter, option: QStyleOptionViewItem, index: QModelIndex) -> None: r = option.rect pencolor = Qt.white if self.theme == 'dark' else Qt.black if self.parent.isEnabled(): if option.state & QStyle.State_Selected: painter.setBrush(QColor(150, 190, 78, 150)) elif option.state & QStyle.State_MouseOver: painter.setBrush(QColor(227, 212, 232)) pencolor = Qt.black else: brushcolor = QColor(79, 85, 87, 175) if self.theme == 'dark' else QColor('#EFF0F1') painter.setBrush(Qt.transparent if index.row() % 2 == 0 else brushcolor) painter.setPen(Qt.NoPen) painter.drawRect(r) thumb = QIcon(index.data(Qt.DecorationRole + 1)) starttime = index.data(Qt.DisplayRole + 1) endtime = index.data(Qt.UserRole + 1) externalPath = index.data(Qt.UserRole + 2) r = option.rect.adjusted(5, 0, 0, 0) thumb.paint(painter, r, Qt.AlignVCenter | Qt.AlignLeft) painter.setPen(QPen(pencolor, 1, Qt.SolidLine)) r = option.rect.adjusted(110, 8, 0, 0) painter.setFont(QFont('Noto Sans UI', 10 if sys.platform == 'darwin' else 8, QFont.Bold)) painter.drawText(r, Qt.AlignLeft, 'FILENAME' if len(externalPath) else 'START') r = option.rect.adjusted(110, 20, 0, 0) painter.setFont(QFont('Noto Sans UI', 11 if sys.platform == 'darwin' else 9, QFont.Normal)) if len(externalPath): painter.drawText(r, Qt.AlignLeft, self.clipText(os.path.basename(externalPath), painter)) else: painter.drawText(r, Qt.AlignLeft, starttime) if len(endtime) > 0: r = option.rect.adjusted(110, 45, 0, 0) painter.setFont(QFont('Noto Sans UI', 10 if sys.platform == 'darwin' else 8, QFont.Bold)) painter.drawText(r, Qt.AlignLeft, 'RUNTIME' if len(externalPath) else 'END') r = option.rect.adjusted(110, 60, 0, 0) painter.setFont(QFont('Noto Sans UI', 11 if sys.platform == 'darwin' else 9, QFont.Normal)) painter.drawText(r, Qt.AlignLeft, endtime) if self.parent.verticalScrollBar().isVisible(): self.parent.setFixedWidth(210) else: self.parent.setFixedWidth(190)
def sizeHint(self, option: QStyleOptionViewItem, index: QModelIndex) -> QSize: return QSize(185, 85)
def index(self, row, column, parent=QtCore.QModelIndex()): if not self.hasIndex(row, column, parent): return QtCore.QModelIndex() parent_item = (self.root_item if not parent.isValid() else parent.internalPointer()) child_item = parent_item.child(row) return self.createIndex(row, column, child_item) if child_item else QtCore.QModelIndex()
def parent(self, index): if not index.isValid(): return QtCore.QModelIndex() child_item = index.internalPointer() parent_item = child_item.parentItem() if parent_item == self.root_item: return QtCore.QModelIndex() return self.createIndex(parent_item.row(), 0, parent_item)
def rowCount(self, parent=QtCore.QModelIndex()): if parent.column() > 0: return 0 parent_item = (self.root_item if not parent.isValid() else parent.internalPointer()) return parent_item.childCount()
def columnCount(self, parent=QtCore.QModelIndex()): return (parent.internalPointer().columnCount() if parent.isValid() else self.root_item.columnCount())
def rowCount(self, parent=QtCore.QModelIndex()): return 0 if self.container is None else len(self.container)
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 index(self, row, column, parent): if not self.hasIndex(row, column, parent): return QtCore.QModelIndex() pitem = parent.internalPointer() if not pitem: pitem = self.rootnode item = pitem.child(row) if not item: return QtCore.QModelIndex() return self.createIndex(row, column, item)
def rowCount(self, parent=QtCore.QModelIndex()): if parent.column() > 0: return 0 pitem = parent.internalPointer() if not pitem: pitem = self.rootnode return len(pitem.children)
def append(self, row, parent=QtCore.QModelIndex()): # pidx = self.createIndex(parent.row(), 0, parent) i = len(self.rows) self.beginInsertRows(parent, i, i) self.rows.append(row) # node = parent.append(rowdata) self.endInsertRows() self.layoutChanged.emit()
def selectRow(self, row): idx = self.model().index(row, 0, QtCore.QModelIndex()) self.setCurrentIndex(idx)
def index(self, row, column, parent=None, *args, **kwargs): if self.hasIndex(row,column,parent): return self.createIndex(row,column,self.m_data[row]) return QModelIndex()
def parent(self, index=None): return QModelIndex()
def insertRows(self): self.beginInsertRows(QModelIndex(), self.m_row_count, self.m_row_count) self.m_data.append([0,0]) self.m_row_count += 1 self.add_mapping(self.color, QRect(0, 0, 2, self.rowCount())) self.endInsertRows() return True