def data(self, QModelIndex, int_role=None): result_couple = self.cmp_res.result_l[QModelIndex.row()] if int_role == Qt.DisplayRole: if QModelIndex.column() == ResultTableMdl.NAME_COLUMN: return result_couple.test_var.name if QModelIndex.column() == ResultTableMdl.ERROR_COLUMN: return '{:.3f}%'.format(result_couple.error) if QModelIndex.column() == ResultTableMdl.STATUS_COLUMN: return result_couple.status if int_role == Qt.ForegroundRole and QModelIndex.column() == ResultTableMdl.STATUS_COLUMN: color = QBrush(Qt.black) if result_couple.status == ResultCouple.STS_KO: #RED color = QBrush(Qt.red) if result_couple.status == ResultCouple.STS_WARN: #YELLOW color = QBrush(QColor(255, 157, 0, 255)) if result_couple.status == ResultCouple.STS_PASS: # Yellowish-GREEN color = QBrush(QColor(153, 204, 0, 255)) if result_couple.status == ResultCouple.STS_MATCH: # GREEN color = QBrush(QColor(0, 204, 0, 255)) return color
def flags(self, index: QModelIndex): flags = super().flags(index) if index.column() in (0, 1, 2, 3): flags |= Qt.ItemIsEditable if index.column() == 0: flags |= Qt.ItemIsUserCheckable return flags
def update_question_type_tools(self, current: QModelIndex = None): if current is not None: self.ui.remove_question_type_button.setDisabled(False) top_index = current.sibling(current.row() - 1, current.column()) bottom_index = current.sibling(current.row() + 1, current.column()) self.ui.move_up_question_type_button.setDisabled(not top_index.isValid()) self.ui.move_down_question_type_button.setDisabled(not bottom_index.isValid()) else: self.ui.remove_question_type_button.setDisabled(True) self.ui.move_up_question_type_button.setDisabled(True) self.ui.move_down_question_type_button.setDisabled(True)
def setData(self, index: QModelIndex, value, role=Qt.DisplayRole): if role == Qt.CheckStateRole: if index.column() == 0: message_type = self.message_types[index.row()] message_type.show = value self.message_type_visibility_changed.emit(message_type) elif role == Qt.EditRole: if index.column() == 0 and value: message_type = self.message_types[index.row()] message_type.name = value self.message_type_name_edited.emit(value) return True
def data(self, index: QModelIndex, role = None): if not index.isValid(): return None item = index.internalPointer() if role == Qt.DisplayRole: return item.data(index.column()) elif role == Qt.CheckStateRole and index.column() == TaskTreeColumn.FileName: return item.selected elif role == Qt.DecorationRole and index.column() == TaskTreeColumn.FileName: # TODO: use with real icons from PyQt5.QtGui import QIcon return QIcon.fromTheme("xware-desktop") return None
def setData(self, index: QModelIndex, value, role=None): if role == Qt.EditRole: i, j = index.row(), index.column() label = self.message_type[i] # type: SimulatorProtocolLabel if j == 0: label.name = value ft = self.controller.field_types_by_caption.get(value, FieldType("Custom", FieldType.Function.CUSTOM)) label.field_type = ft elif j == 1: label.display_format_index = value elif j == 2: label.value_type_index = value elif j == 3: if label.value_type_index == 0: message = label.parent() try: bits = util.convert_string_to_bits(value, label.display_format_index, target_num_bits=label.end-label.start) message.plain_bits[label.start:label.end] = bits except ValueError: pass elif label.value_type_index == 2: label.formula = value elif label.value_type_index == 3: label.external_program = value elif label.value_type_index == 4: label.random_min = value[0] label.random_max = value[1] self.dataChanged.emit(self.index(i, 0), self.index(i, self.columnCount())) self.protocol_label_updated.emit(label) return True
def setData(self, index: QModelIndex, value: QVariant, role: int = None): if not index.isValid(): return False item = index.internalPointer() if role == Qt.CheckStateRole: childrenCount = item.childrenCount() if childrenCount: for i in range(childrenCount): self.setData(index.child(i, 0), value, role = role) else: item.selected = bool(value) self.dataChanged.emit(index, index, [Qt.CheckStateRole]) # recalculate parents p = index while True: p = p.parent() if p.isValid(): self.dataChanged.emit(p, p, [Qt.CheckStateRole]) else: break # success return True if role == Qt.EditRole: assert index.column() == TaskTreeColumn.FileName item.setNameByUser(value) self.dataChanged.emit(index, index, [Qt.DisplayRole]) return True return False
def selectSample(self,index: QModelIndex): print("select row",index.row(),"column",index.column(),"id",index.internalId()) self.currentWell=self.sampleTable.item(index.row(),1).text() print("sample item=",self.sampleTable.item(index.row(),0).text()) self.currentSample=int(self.sampleTable.item(index.row(),0).text()) #self.plateTable.selectRow(index.row()) self.refreshAll()
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) elif j == 4: participant.address_hex = value self.update() self.participant_edited.emit() return True
def data(self, index: QModelIndex, role=Qt.DisplayRole): if not index.isValid(): return None i = index.row() j = index.column() device = self.get_device_at(i) if role == Qt.DisplayRole: if j == 0: return self.backend_handler.DEVICE_NAMES[i] elif j == 1: if device.is_enabled: if device.supports_rx and device.supports_tx: device_info = "supports RX and TX" elif device.supports_rx and not device.supports_tx: device_info = "supports RX only" elif not device.supports_rx and device.supports_tx: device_info = "supports TX only" else: device_info = "" else: device_info = "disabled" return device_info elif j == 2: return "" if device.has_native_backend else "not available" elif j == 3: return "" if device.has_gnuradio_backend else "not available" elif role == Qt.CheckStateRole: if j == 0 and (device.has_native_backend or device.has_gnuradio_backend): return Qt.Checked if device.is_enabled else Qt.Unchecked elif j == 2 and device.has_native_backend: return Qt.Checked if device.selected_backend == Backends.native else Qt.Unchecked elif j == 3 and device.has_gnuradio_backend: return Qt.Checked if device.selected_backend == Backends.grc else Qt.Unchecked
def setData(self, index: QModelIndex, value, role=Qt.EditRole): if value == "": return True i = index.row() j = index.column() if i >= len(self.message_type): return False lbl = self.__get_label_at(i) if j == 0: lbl.name = value type_before = type(lbl) self.message_type.change_field_type_of_label(lbl, self.field_types_by_caption.get(value, None)) lbl = self.__get_label_at(i) if type_before != ProtocolLabel or type(lbl) != ProtocolLabel: self.special_status_label_changed.emit(lbl) elif j == 1: lbl.start = self.message.convert_index(int(value - 1), from_view=self.proto_view, to_view=0, decoded=True)[ 0] elif j == 2: lbl.end = self.message.convert_index(int(value), from_view=self.proto_view, to_view=0, decoded=True)[0] elif j == 3: lbl.color_index = value elif j == 4: if bool(value) != lbl.apply_decoding: lbl.apply_decoding = bool(value) self.apply_decoding_changed.emit(lbl) return True
def setData(self, index: QModelIndex, value, role=Qt.DisplayRole): if role != Qt.EditRole: return True i = index.row() j = index.column() a = self.get_alignment_offset_at(i) j -= a hex_chars = ("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f") if i >= len(self.protocol.messages): return False if self.proto_view == 0 and value in ("0", "1") and self.__pad_until_index(i, j + 1): self.protocol.messages[i][j] = bool(int(value)) self.display_data[i][j] = int(value) elif self.proto_view == 1 and value in hex_chars and self.__pad_until_index(i, (j + 1) * 4): converted_j = self.protocol.convert_index(j, 1, 0, self.decode, message_indx=i)[0] bits = "{0:04b}".format(int(value, 16)) for k in range(4): self.protocol.messages[i][converted_j + k] = bool(int(bits[k])) self.display_data[i][j] = int(value, 16) elif self.proto_view == 2 and len(value) == 1 and self.__pad_until_index(i, (j + 1) * 8): converted_j = self.protocol.convert_index(j, 2, 0, self.decode, message_indx=i)[0] bits = "{0:08b}".format(ord(value)) for k in range(8): self.protocol.messages[i][converted_j + k] = bool(int(bits[k])) self.display_data[i][j] = ord(value) else: return False self.data_edited.emit(i, j) return True
def lessThan(self, first: QModelIndex, second: QModelIndex): """ Returns true if the value of the item referred to by the given index 'first' is less than the value of the item referred to by the given index 'second', otherwise returns false. """ first_data = self.sourceModel().data(first, Qt.DisplayRole) second_data = self.sourceModel().data(second, Qt.DisplayRole) if first.column() == ResultTableMdl.STATUS_COLUMN: if first_data == ResultCouple.STS_KO: if second_data in [ResultCouple.STS_WARN, ResultCouple.STS_PASS, ResultCouple.STS_MATCH]: return True if first_data == ResultCouple.STS_WARN: if second_data in [ResultCouple.STS_PASS, ResultCouple.STS_MATCH]: return True if first_data == ResultCouple.STS_PASS: if second_data in [ResultCouple.STS_MATCH]: return True # in any other case return False else: # keep the usual order if user is not ordering by status return super().lessThan(first, second)
def data(self, index: QModelIndex, role=Qt.DisplayRole): i, j = index.row(), index.column() if role == Qt.DisplayRole: try: lbl = self.message_type[i] except IndexError: return False if j == 0: return lbl.name elif j == 1: return self.message.get_label_range(lbl, view=self.proto_view, decode=True)[0] + 1 elif j == 2: return self.message.get_label_range(lbl, view=self.proto_view, decode=True)[1] elif j == 3: return lbl.color_index elif j == 4: return lbl.apply_decoding elif role == Qt.TextAlignmentRole: return Qt.AlignCenter elif role == Qt.FontRole and j == 0: font = QFont() font.setItalic(self.message_type[i].field_type is None) return font else: return None
def on_commitData(editor: QLineEdit): new_text = editor.text() idx = QModelIndex(self.opened) row, col = idx.row(), idx.column() _prior_text, user_role = self.tv.text_txid_from_coordinate(row, col) # check that we didn't forget to set UserRole on an editable field assert user_role is not None, (row, col) self.tv.on_edited(idx, user_role, new_text)
def link_index(self, index: QModelIndex): try: lbl = self.message_type[index.row()] # type: SimulatorProtocolLabel if index.column() == 2 and lbl.is_checksum_label: return True except: return False return False
def flags(self, index: QModelIndex): result = Qt.ItemIsEnabled | Qt.ItemIsSelectable if index.column() == TaskTreeColumn.FileName: result |= Qt.ItemIsUserCheckable | Qt.ItemIsTristate if index.row() == 0: result |= Qt.ItemIsEditable return result
def data(self, index: QModelIndex, role=Qt.DisplayRole): if not index.isValid(): return None i, j = index.row(), index.column() try: lbl = self.display_labels[i] except IndexError: return None if not lbl or not self.message: return None if isinstance(lbl, ChecksumLabel): calculated_crc = lbl.calculate_checksum_for_message(self.message, use_decoded_bits=True) else: calculated_crc = None if role == Qt.DisplayRole: if j == 0: return lbl.name elif j == 1: return lbl.DISPLAY_FORMATS[lbl.display_format_index] elif j == 2: start, end = self.message.get_label_range(lbl, lbl.display_format_index % 3, True) if lbl.display_format_index in (0, 1, 2): try: data = self.bit_str[self.message_index][start:end] if lbl.display_format_index == 0 \ else self.hex_str[self.message_index][start:end] if lbl.display_format_index == 1 \ else self.ascii_str[self.message_index][start:end] if lbl.display_format_index == 2 \ else "" except IndexError: return None else: # decimal try: data = str(int(self.bit_str[self.message_index][start:end], 2)) except (IndexError, ValueError): return None if calculated_crc is not None: data += " (should be {0})".format(util.convert_bits_to_string(calculated_crc, lbl.display_format_index)) return data elif role == Qt.BackgroundColorRole: if isinstance(lbl, ChecksumLabel): start, end = self.message.get_label_range(lbl, 0, True) if calculated_crc == self.message.decoded_bits[start:end]: return constants.BG_COLOR_CORRECT else: return constants.BG_COLOR_WRONG else: return None
def paint(self, painter: QPainter, option: QStyleOptionViewItem, model_index: QModelIndex): column = model_index.column() new_rect = QRect(option.rect) if column == NAME_COL: # Part Name option.displayAlignment = Qt.AlignVCenter QStyledItemDelegate.paint(self, painter, option, model_index) if column == LOCKED_COL: # Visibility element = _QCOMMONSTYLE.PE_IndicatorCheckBox styleoption = QStyleOptionButton() styleoption.rect = new_rect checked = model_index.model().data(model_index, Qt.EditRole) styleoption.state |= QStyle.State_On if checked else QStyle.State_Off # make the check box look a little more active by changing the pallete styleoption.palette.setBrush(QPalette.Button, Qt.white) styleoption.palette.setBrush(QPalette.HighlightedText, Qt.black) _QCOMMONSTYLE.drawPrimitive(element, styleoption, painter) if checked: # element = _QCOMMONSTYLE.PE_IndicatorMenuCheckMark # _QCOMMONSTYLE.drawPrimitive(element, styleoption, painter) # _QCOMMONSTYLE.drawItemText(painter, new_rect, Qt.AlignCenter, styleoption.palette, True, 'L') icon = QPixmap(":/outlinericons/lock") _QCOMMONSTYLE.drawItemPixmap(painter, new_rect, Qt.AlignCenter, icon) if column == VISIBLE_COL: # Visibility element = _QCOMMONSTYLE.PE_IndicatorCheckBox styleoption = QStyleOptionButton() styleoption.rect = new_rect checked = model_index.model().data(model_index, Qt.EditRole) styleoption.state |= QStyle.State_On if checked else QStyle.State_Off # make the check box look a little more active by changing the pallete styleoption.palette.setBrush(QPalette.Button, Qt.white) styleoption.palette.setBrush(QPalette.HighlightedText, Qt.black) _QCOMMONSTYLE.drawPrimitive(element, styleoption, painter) if checked: # element = _QCOMMONSTYLE.PE_IndicatorMenuCheckMark # _QCOMMONSTYLE.drawPrimitive(element, styleoption, painter) icon = QPixmap(":/outlinericons/eye") _QCOMMONSTYLE.drawItemPixmap(painter, new_rect, Qt.AlignCenter, icon) elif column == COLOR_COL: # Color # Alternate way to get color # outline_tw = self.parent() # item = outline_tw.itemFromIndex(model_index) # color = item.getColor() # print("COLOR_COL", item) color = model_index.model().data(model_index, Qt.EditRole) element = _QCOMMONSTYLE.PE_IndicatorCheckBox styleoption = QStyleOptionViewItem() brush = getBrushObj(color) styleoption.palette.setBrush(QPalette.Button, brush) styleoption.rect = new_rect _QCOMMONSTYLE.drawPrimitive(element, styleoption, painter) else: QStyledItemDelegate.paint(self, painter, option, model_index)
def selectPlate(self,index: QModelIndex): print("select row",index.row(),"column",index.column(),"id",index.internalId()) rec=self.plateTable.model().record(index.row()) for i in range(rec.count()): print(rec.fieldName(i),"=",rec.field(i).value()) self.currentPlate=rec.field(0).value() #self.plateTable.selectRow(index.row()) self.currentSample=None self.currentWell=None self.refreshAll()
def data(self, index: QtCore.QModelIndex, role=QtCore.Qt.DisplayRole): if index.isValid(): ip = index.internalPointer() if index.column() == 0: if role == QtCore.Qt.DisplayRole: return ("*" if ip.unfinished() else "") + ip.title() elif role == QtCore.Qt.ToolTipRole: return ip.tooltip() elif role == QtCore.Qt.DecorationRole: return ip.image()
def flags(self, index: QtCore.QModelIndex) -> QtCore.Qt.ItemFlags: flags = super().flags(index) if not index.isValid(): return flags flags |= QtCore.Qt.ItemIsDragEnabled file_item = self.item(index) if index.column() == 0: flags |= QtCore.Qt.ItemIsEditable if file_item.is_dir: flags |= QtCore.Qt.ItemIsDropEnabled return flags
def data(self, index: QtCore.QModelIndex, role: int=QtCore.Qt.DisplayRole) -> QtCore.QVariant: if not index.isValid(): return QtCore.QVariant() if index.column() < 0 or index.column() >= self.columnCount: return QtCore.QVariant() if role == QtCore.Qt.DisplayRole or role == QtCore.Qt.EditRole: return self.item(index).data[index.column()] if index.column() == 0: for case in switch(role): if case(QtWidgets.QDirModel.FileIconRole): return self.file_icon if not self.item(index).is_dir else \ self.folder_icon if case(): return QtCore.QVariant() return QtCore.QVariant()
def tilesChanged(self, tiles): if (tiles.first().tileset() != self.mTileset): return topLeft = QModelIndex() bottomRight = QModelIndex() for tile in tiles: i = self.tileIndex(tile) if (not topLeft.isValid()): topLeft = i bottomRight = i continue if (i.row() < topLeft.row() or i.column() < topLeft.column()): topLeft = self.index(min(topLeft.row(), i.row()), min(topLeft.column(), i.column())) if (i.row() > bottomRight.row() or i.column() > bottomRight.column()): bottomRight = self.index(max(bottomRight.row(), i.row()), max(bottomRight.column(), i.column())) if (topLeft.isValid()): self.dataChanged.emit(topLeft, bottomRight)
def data(self, index: QModelIndex, role=Qt.DisplayRole): if not index.isValid(): return None i = index.row() j = index.column() if role == Qt.DisplayRole and self.display_data: if self.label_mask[i, j]: return "." return super().data(index, role)
def flags(self, index: QModelIndex): if index.isValid(): alignment_offset = self.get_alignment_offset_at(index.row()) if index.column() < alignment_offset: return Qt.ItemIsSelectable | Qt.ItemIsEnabled if self.is_writeable: return Qt.ItemIsEnabled | Qt.ItemIsEditable | Qt.ItemIsSelectable else: return Qt.ItemIsEnabled | Qt.ItemIsSelectable else: return Qt.NoItemFlags
def data(self, index: QModelIndex, role: int = Qt.DisplayRole) -> Optional[str]: """Qt override.""" if index.isValid() and role == Qt.DisplayRole: obj = self.listdata[index.row()] colname = self.header_attr[index.column()] thing = getattr(obj, colname) if callable(thing): return str(thing()) else: return str(thing) return None
def selectRun(self,index: QModelIndex): print("select row",index.row(),"column",index.column(),"id",index.internalId()) pkIndex=index.sibling(index.row(),0) self.currentRun=self.runsTable.model().data(pkIndex).value() pgmIndex=index.sibling(index.row(),3) self.currentProgram=self.runsTable.model().data(pgmIndex).value() self.currentPlate=None self.currentSample=None self.currentWell=None #self.runsTable.selectRow(index.row()) self.refreshAll()
def setEditorData(self, editor: QWidget, model_index: QModelIndex): column = model_index.column() if column == NAME_COL: # Part Name text_QString = model_index.model().data(model_index, Qt.EditRole) editor.setText(text_QString) # elif column == VISIBLE_COL: # Visibility # value = model_index.model().data(model_index, Qt.EditRole) # editor.setChecked(value) elif column == COLOR_COL: # Color value = model_index.model().data(model_index, Qt.EditRole) editor.setCurrentColor(QColor(value)) else: QStyledItemDelegate.setEditorData(self, editor, model_index)
def data(self, index: QModelIndex, role=Qt.DisplayRole): if not index.isValid(): return None i, j = index.row(), index.column() if role == Qt.DisplayRole: data_range = self.checksum_label.data_ranges[i] if j == 0: return self.message.convert_index(data_range[0], 0, self.proto_view, True)[0] + 1 elif j == 1: return self.message.convert_index(data_range[1], 0, self.proto_view, True)[0] return None
def table_item_clicked(self, index_clicked: QModelIndex): col = index_clicked.column() row = index_clicked.row() if col == 0: self.switch_canvas_from_table(row) elif col == 1: # if row <= self.active_canvas: origin_state = self.canvasNameTableModel.is_visible[row] is_visible = self.canvasNameTableModel.set_canvas_visible( row, not origin_state) # self.canvas[row].switch_visible(is_visible) self.canvas[row].setVisible(is_visible) self.canvasNameTableModel.layoutChanged.emit()
def flags(self, index: QtCore.QModelIndex) -> int: """Get flags which influence the display of cells :param index: index referencing the cell. :type index: QModelIndex :return: flags :rtype: int """ flags = QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemNeverHasChildren | QtCore.Qt.ItemIsSelectable key = self.nameForRow(index.row()) if self._data[key][1] is None and index.column() == 3: # the theta dihedral is not editable for alpha-amino acids return flags else: return QtCore.Qt.ItemIsEditable | flags
def data(self, index: QModelIndex, role=Qt.DisplayRole): if role == Qt.DisplayRole: i = index.row() j = index.column() part = self.participants[i] if j == 0: return part.name elif j == 1: return part.shortname elif j == 2: return part.color_index elif j == 3: return part.relative_rssi elif j == 4: return part.address_hex
def setData(self, index: QModelIndex, value: typing.Any, role: int = ...) -> bool: row, col = index.row(), index.column() if role == Qt.EditRole: color = QColor(value) if color.isValid(): self._colors[row][col] = color self.dataChanged.emit(index, index) return True return False
def data(self, QModelIndex, role=None): if not QModelIndex.isValid(): print("行或者列有问题") return QVariant() # if role == Qt.TextAlignmentRole: # return int(Qt.AlignRight | Qt.AlignVCenter) # elif role == Qt.DisplayRole: # row = QModelIndex.row() # column = QModelIndex.column() # return self.currencyMap.get('data')[row][column] # # print("查数据") # row = QModelIndex.row() # # print('role:',role) # if role is None: # return self.currencyMap.get('data')[row] elif role != Qt.DisplayRole: # print("123") return QVariant() table_data = self.data_[QModelIndex.row()][QModelIndex.column()] if isinstance(table_data, list): if isinstance(table_data[0], int): if table_data[0] > 1262275200: table_data = [ self.time_stamp_to_str(x) for x in table_data ] table_data = ",".join(table_data) return QVariant(table_data) else: table_data = [str(x) for x in table_data] x = ",".join(table_data) return QVariant(x) else: table_data = [str(x) for x in table_data] x = ",".join(table_data) return QVariant(x) return QVariant(self.data_[QModelIndex.row()][QModelIndex.column()])
def data(self, index: QModelIndex, role: int = Qt.DisplayRole): if not index.isValid() or self.df.empty: return None row = index.row() col = index.column() value = self.df.iat[row, col] if role == Qt.DisplayRole: return str(value) elif role == Qt.TextAlignmentRole: return Qt.AlignCenter else: return None
def data(self, index: QModelIndex, role: int = Qt.DisplayRole) -> Any: """Переопределяет соответствующий родительский метод. data(self, index: QModelIndex, role: int = Qt.DisplayRole) -> Any """ assert self.checkIndex(index) # if role is None: # role = Qt.DisplayRole if role == Vns.ItemDataRole.ItemDict: assert index.isValid() indexWithZeroColumn = self.sibling(index.row(), self.ZERO_COLUMN, index) return self.__localDataModel.data( self._mapToLocal(indexWithZeroColumn), role) elif role == Vns.ItemDataRole._ChildrenLoadingInfo: return None elif role == Vns.ItemDataRole.ChildrenAreLoadedSeparately: return self.childrenAreLoadedSeparately(index) elif role == Vns.ItemDataRole.ChildrenLoadingPolicy: return self.childrenLoadingPolicy( index) # if self.childrenAreLoadedSeparately(index) else None elif role == Vns.ItemDataRole.ChildrenLoadingState: return self.childrenLoadingState( index) # if self.childrenAreLoadedSeparately(index) else None elif role == Vns.ItemDataRole.ChildrenPagination: return self.childrenPagination( index) # if self.childrenAreLoadedSeparately(index) else None elif role == Vns.ItemDataRole._DetailsLoadingInfo: return None elif role == Vns.ItemDataRole.DetailsAreLoadedSeparately: return self.detailsAreLoadedSeparately(index) elif role == Vns.ItemDataRole.DetailsAreLoaded: return self.hasLoadedDetails( index) # if self.detailsAreLoadedSeparately(index) else None elif role == Vns.ItemDataRole.DetailsLoadingState: return self.detailsLoadingState( index) # if self.detailsAreLoadedSeparately(index) else None assert not (Vns.ItemDataRole.First <= role < Vns.ItemDataRole.Custom) if __debug__ and role == Qt.DisplayRole and index.isValid( ) and index.column() == self.ZERO_COLUMN: # Этот костыль нужен, чтобы в представлении отображались хоть какие-то данные в режиме отладки. return "debug: [the item]" return self.__localDataModel.data(self._mapToLocal(index), role)
def data(self, index: QModelIndex, role=Qt.DisplayRole): if not index.isValid(): return None if role == Qt.DisplayRole or role == Qt.EditRole: i = index.row() j = index.column() fieldtype = self.field_types[i] if j == 0: return fieldtype.caption elif j == 1: return fieldtype.function.name elif j == 2: return ProtocolLabel.DISPLAY_FORMATS[ fieldtype.display_format_index]
def data(self, index: QModelIndex, role: int = None) -> Any: if not index.isValid(): return None elif role != QtCore.Qt.DisplayRole: return None if index.row() >= 0 and (index.row() < len(self.dataCache)): if index.row() in self.pendingUpdates: return "--- Saving ---" try: # logger.debug("data role: %r, %r, %r", index.row(), index.column(), self._validFields) return self.dataCache[index.row()][self.fields[index.column()]] except Exception as err: logger.exception(err) return "" else: return "--- Lade ---"
def data(self, index: QModelIndex, role: int = Qt.DisplayRole) -> typing.Any: if role == Qt.DisplayRole: row = index.row() column = index.column() if column == 0: return self._plugins[row][0] elif column == 1: try: return self._plugins[row][1].__version__ except AttributeError: return elif role == PluginsModel.PluginRole: return self._plugins[index.row()][1] return super().data(index, role)
def data(self, index: qc.QModelIndex, role) -> typing.Any: col = index.column() row = index.row() if role == qc.Qt.UserRole: return self.l[row] if role == qc.Qt.DisplayRole or role == qc.Qt.ToolTipRole or role == qc.Qt.EditRole: if col == SwitchCaseModelColumn.Value: return self.l[row].value if col == SwitchCaseModelColumn.Event: event = self.l[row].event if role == qc.Qt.EditRole: return event if event is _PLACEHOLDER_EVENT: return '<placeholder>' return f'{util.get_event_full_description(event)}' return qc.QVariant()
def flags(self, index: QModelIndex) -> Qt.ItemFlags: if not index.isValid(): return Qt.NoItemFlags if (index.column() != VALUE_COLUMN and not isinstance(index.data(OBJECT_ROLE), DictItem)) \ or self.hasChildren(index): return Qt.ItemIsEnabled | Qt.ItemIsSelectable # FIXME check if other types are also editable if isinstance(index.data(OBJECT_ROLE), (DictItem, Enum, bool, int, float, str, bytes, type(None), dict, list, AbstractSet)): return Qt.ItemIsEditable | Qt.ItemIsEnabled | Qt.ItemIsSelectable return Qt.ItemIsEnabled | Qt.ItemIsSelectable
def lessThan(self, left: QModelIndex, right: QModelIndex) -> bool: left_data = self.sourceModel().data(left) right_data = self.sourceModel().data(right) col = left.column() if col in self.filter_method: method = self.filter_method[col] if method == "Number": return float(left_data) < float(right_data) elif method == "Regex": return left_data < right_data elif method == "Date": left_data = QDate.fromString(left_data, "yyyy-MM-dd") right_data = QDate.fromString(right_data, "yyyy-MM-dd") return left_data < right_data return False
def updateEditorGeometry(self, editor: QWidget, option: QStyleOptionViewItem, model_index: QModelIndex): column = model_index.column() if column == NAME_COL: editor.setGeometry(option.rect) # elif column == VISIBLE_COL: # rect = QRect(option.rect) # delta = option.rect.width() / 2 - 9 # rect.setX(option.rect.x() + delta) # Hack to center the checkbox # editor.setGeometry(rect) # elif column == COLOR_COL: # editor.setGeometry(option.rect) else: QStyledItemDelegate.updateEditorGeometry(self, editor, option, model_index)
def data(self, index: QModelIndex, role: int = None): row, col = index.row(), index.column() value = self._data[row][col] if role == Qt.SizeHintRole: return QSize(120, 50) if role == Qt.TextAlignmentRole: pass # if isnumeric(value): # return Qt.AlignVCenter + Qt.AlignVertical_Mask if role == Qt.BackgroundColorRole: if (row, col) in [(x['row'], x['column']) for x in self.modified]: return QVariant(QColor("#facaca")) if role == Qt.EditRole: return retranslate_delimiter(value) if role == Qt.DisplayRole: return retranslate_delimiter(value)
def setData(self, index: QModelIndex, value, role: int = Qt.EditRole): if role != Qt.EditRole or not index.isValid(): return False row = index.row() col = index.column() if col == 0: self.variables.at[row, 'Checked'] = True if value == 1 else False self.dataChanged.emit(index.sibling(row, col + 1), index.sibling(row, self.columnCount())) return True return False
def data(self, index: QModelIndex, role: int = ...): if not index.isValid(): return QVariant() item = index.internalPointer() col = index.column() if role == Qt.DisplayRole: if col == 0: return str(item.key()) elif col == 1: return str(item.value()) elif col == 2: return str(item.type()) return QVariant()
def rowCount(self, parent: QModelIndex = QModelIndex()): if self.sourceModel() is None: return 0 depth = Id.depth(parent) if depth == Id.Depth.Invalid: return self.sourceModel().rowCount() if depth != Id.Depth.D0: return 0 if parent.column() != 0: return 0 requirements, dependents = self.sourceModel().data( self.mapToSource(parent), Role.Associations) if self._dataType == DataType.Requires: return len(requirements) else: return len(dependents)
def createEditor(self, parent: QWidget, option: QStyleOptionViewItem, index: QModelIndex) -> QWidget: """ Creates an editor widget for the given index. Derived function. :param parent: parent QWidget :param option: QStyleOptionViewItem :param index: model index for editor creation :return: QWidget which represents the editor for the given model index """ if index.isValid(): if index.column() == 1 and not self.__only_numbers: combobox = QComboBox(parent) combobox.addItems(["Integer", "Float", "String"]) combobox.setFocusPolicy(Qt.StrongFocus) return combobox return super().createEditor(parent, option, index)
def rowCount( self, parent: QtCore.QModelIndex = QtCore.QModelIndex()) -> int: if parent.column() > 0: # pragma: no coverage return 0 if not parent.isValid(): return len(self.__root_item.children) parent_item = parent.internalPointer() if parent_item is None: return 0 if isinstance(parent_item, AbstractFolder): return len(parent_item.children) else: return 0
def setData(self, index: QtCore.QModelIndex, value: typing.Any, role: int = ...) -> bool: index_row = index.row() index_column = index.column() if index_row == index_column: # Shouldn't happen. return False unit_horizontal = self._unit_list[index_column] unit_vertical = self._unit_list[index_row] factor = unit_horizontal.factor if factor is None: # Bug from initializing the database with wrong defaults factor = 1.0 if unit_vertical in data.IngredientUnit.base_units.values(): # Should also not happen - flags should have been set return False value = nullify(value) _translate = translate if value is None: self.illegalValue.emit(misc.IllegalValueEntered.ISEMPTY, None) return False try: value = float(parse_decimal(value)) except NumberFormatError: # The user has entered something strange. self.illegalValue.emit(misc.IllegalValueEntered.ISNONUMBER, value) return False if value == 0: self.illegalValue.emit(misc.IllegalValueEntered.ISZERO, "0") return False if value < 0.0: self.illegalValue.emit(misc.IllegalValueEntered.ISNONUMBER, str(value)) return False self.changed.emit() unit_vertical.factor = value * factor if unit_horizontal.factor is None: # Compensate for init bug unit_horizontal.factor = 1.0 self.reload_model() return True
def setData(self, index: QModelIndex, value: QVariant, role=None): if index.isValid() and role == Qt.EditRole: entry: Dict[str, str] = self.timeContent[index.row()] if index.column() not in [0, 1]: return False pos: Tuple[int, int] = (index.row(), index.column()) inputRaw = value inputFormatted: str = inputRaw # right format continue processing if len(inputRaw) <= 0: if index.column() == 0: inputFormatted = entry[TimeTableModel.FROM_TIME_KEY] elif index.column() == 1: inputFormatted = entry[TimeTableModel.TO_TIME_KEY] elif re.match('[0-9]{2}:[0-9]{2}', inputRaw): inputFormatted = inputRaw if pos in self.invalidElements: self.invalidElements.remove(pos) elif re.match('[0-9]{1,2}[.:/,][0-9]{1,2}', inputRaw): inputFormatted = ':'.join([n.zfill(2) for n in re.split('[.:/,]', inputRaw)]) if pos in self.invalidElements: self.invalidElements.remove(pos) elif re.match('[0-9]{1,4}', re.sub('[^0-9]', '', inputRaw)): inputTrimmed = re.sub('[^0-9]', '', inputRaw).zfill(4) inputFormatted = ':'.join([inputTrimmed[:-2], inputTrimmed[-2:]]) if pos in self.invalidElements: self.invalidElements.remove(pos) elif len(inputRaw) > 0: self.invalidElements.append(pos) if index.column() == 0: entry[TimeTableModel.FROM_TIME_KEY] = inputFormatted elif index.column() == 1: entry[TimeTableModel.TO_TIME_KEY] = inputFormatted self.updateRow(pos[0]) self.dataChanged.emit(self.createIndex(index.row(), 0), self.createIndex(index.row(), 2)) if entry[TimeTableModel.FROM_TIME_KEY] != '' and \ (index.row(), 0) not in self.invalidElements: if entry[TimeTableModel.TO_TIME_KEY] == '' and \ (index.row(), 1) not in self.invalidElements: self.updateTimer.start() else: self.updateTimer.stop() return True
def data(self, idx: QModelIndex, role=None): if role == Qt.TextAlignmentRole and idx.column() in (3, 4, 5): return Qt.AlignCenter if not idx.isValid(): return None perm_obj = self._data[idx.row()] if role == Qt.EditRole and idx.column() in (1, 5): return perm_obj.address if role != Qt.DisplayRole: return None if idx.column() == 0: if self._alias_list and perm_obj.address in self._alias_list.keys( ): return self._alias_list[perm_obj.address] return '' if idx.column() == 1: return perm_obj.address if idx.column() == 2: if self._perm_type == enums.MINE: if perm_obj.address in self.last_mined: return timeago.format(self.last_mined[perm_obj.address], datetime.now()) if self._perm_type == enums.ADMIN: if perm_obj.address in self.last_voted: return timeago.format(self.last_voted[perm_obj.address], datetime.now()) return 'Never' if idx.column() == 3: if self._perm_type == enums.MINE: return "{} Blocks".format( self.last_24_h_mine_count[perm_obj.address] if perm_obj. address in self.last_24_h_mine_count else 0) else: return "{} Votes".format( self.last_24_h_vote_count[perm_obj.address] if perm_obj. address in self.last_24_h_vote_count else 0) if idx.column() == 4: return "{} of {}".format( self.count_revokes[perm_obj.address] if perm_obj.address in self.count_revokes else 0, math.ceil(self.num_guardians * ADMIN_CONSENUS_ADMIN if self._perm_type == enums.ADMIN else ADMIN_CONSENUS_MINE))
def setData(self, index: QModelIndex, value, role=Qt.DisplayRole): if role != Qt.EditRole: return True i = index.row() j = index.column() a = self.get_alignment_offset_at(i) j -= a hex_chars = ("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f") if i >= len(self.protocol.messages): return False if self.proto_view == 0 and value in ("0", "1") and self.__pad_until_index( i, j + 1): self.protocol.messages[i][j] = bool(int(value)) self.display_data[i][j] = int(value) elif self.proto_view == 1 and value in hex_chars and self.__pad_until_index( i, (j + 1) * 4): converted_j = self.protocol.convert_index(j, 1, 0, self.decode, message_indx=i)[0] bits = "{0:04b}".format(int(value, 16)) for k in range(4): self.protocol.messages[i][converted_j + k] = bool(int(bits[k])) self.display_data[i][j] = int(value, 16) elif self.proto_view == 2 and len( value) == 1 and self.__pad_until_index(i, (j + 1) * 8): converted_j = self.protocol.convert_index(j, 2, 0, self.decode, message_indx=i)[0] bits = "{0:08b}".format(ord(value)) for k in range(8): self.protocol.messages[i][converted_j + k] = bool(int(bits[k])) self.display_data[i][j] = ord(value) else: return False self.data_edited.emit(i, j) return True
def data(self, index: QModelIndex, role=QtDisplayRole): if not index.isValid(): return None # if role == QtDisplayRole: # retValue = super().data( index, role ) # if retValue is None or retValue == "None": # return "-" # return retValue if role == QtTextAlignmentRole: if index.column() == 10: ## notes return QtAlignLeft | QtAlignVCenter # return Qt.AlignHCenter | QtAlignVCenter return super().data(index, role)
def data(self, qindex: QModelIndex, role=None): if role == Qt.DisplayRole or role == Qt.EditRole: entry = self.entries[qindex.row()] attr = self.columns[qindex.column()] value = getattr(entry, attr) if attr in ("gmd_name_index", "gmd_description_index"): return get_t9n(self.model, "t9n", value) elif attr == "kire_id": kire_model = self.model.get_relation_data("kire") if kire_model is None: return None else: return kire_model.entries[value] return value elif role == Qt.UserRole: entry = self.entries[qindex.row()] return entry
def dataChangeEvent(self, index_0: QModelIndex, new: str, old: str): if not index_0.isValid(): return chg_row = index_0.row() chg_col = index_0.column() if chg_col < len(self.cols.keys()): return if chg_row == 0: item = self.model.itemFromIndex(index_0) item.setText(new) return last_row = self.model.rowCount() - 1 if chg_row != 0: item = self.model.item(0, chg_col) total = item.text().strip() if total == '': total = '0x0' total = self.tobinary(total, width=32)[::-1] total = list(total) # print(len(total), total) values = self.dataformat.get(chg_row) msb = values[0] lsb = values[1] width = msb - lsb + 1 value_chg = new value_chg = list(self.tobinary(value_chg, width=width)[::-1])[0:width] total[lsb:msb + 1] = value_chg total = ''.join(total[0:32]) item.setText(self.binary2hex(total[::-1], width=8)) item_chg = self.model.itemFromIndex(index_0) value_chg = ''.join(value_chg)[::-1] item_chg.setText(self.binary2hex(value_chg, width=width // 4)) else: total = new total = self.tobinary(total, width=32)[::-1] for row, values in self.dataformat.items(): msb = values[0] lsb = values[1] width = msb - lsb + 1 item = self.model.item(row, chg_col) item.setText( self.binary2hex(total[lsb:msb + 1][::-1], width=width // 4))
def setData(self, index: QModelIndex, value, role=Qt.DisplayRole): if value == "": return True i = index.row() j = index.column() if i >= len(self.protocol_labels): return False lbl = self.protocol_labels[i] proto = self.proto_group.decoded_bits_str if j == 0: lbl.name = value elif j == 1: new_start = int( self.proto_group.convert_index( int(value) - 1, self.proto_view, 0, True, i)[0]) lbl.start = new_start # lbl.refblock passt hier wahrscheinlich nicht lbl.reference_bits = proto[lbl.refblock][lbl.start:lbl.end] lbl.find_block_numbers(proto) elif j == 2: new_end = int( self.proto_group.convert_index( int(value) - 1, self.proto_view, 0, True, i)[1]) + 1 lbl.end = new_end lbl.reference_bits = proto[lbl.refblock][lbl.start:lbl.end] lbl.find_block_numbers(proto) elif j == 3: lbl.restrictive = value lbl.reference_bits = proto[lbl.refblock][lbl.start:lbl.end] self.restrictive_changed.emit(i, value) lbl.find_block_numbers(proto) elif j == 4: lbl.refblock = int(value) - self.offset - 1 lbl.reference_bits = proto[lbl.refblock][lbl.start:lbl.end] lbl.find_block_numbers(proto) elif j == 5: lbl.color_index = value elif j == 6: lbl.apply_decoding = bool(value) elif j == 7: self.remove_label(self.protocol_labels[i]) return True
def data(self, index: QModelIndex, role=None): task_enums = list(self._data.entries.keys()) task_id = task_enums[index.row()] entry = self._data.entries[task_id] column = index.column() def duration(secs): if secs > 0: return datetime.timedelta(seconds=float(secs)) else: return '' if role == Qt.DisplayRole: if column == 0: return str(duration(entry.last_started_at)) if column == 1: return str(duration(entry.last_stopped_at)) if column == 2: if entry.last_stopped_at >= entry.last_started_at: return str(duration(entry.last_stopped_at - entry.last_started_at)) else: return str(duration(self._data.timestamp - entry.last_started_at)) if column == 3: return str(duration(entry.total_run_time)) if column == 4: return str(entry.number_of_times_started) if column == 5: return str(entry.number_of_times_failed) if column == 6: return str(entry.last_exit_code) raise ValueError(f'Invalid column index: {column}') if role == Qt.TextAlignmentRole: return Qt.AlignCenter if role == Qt.DecorationRole: pass # Return icons if necessary return QVariant()
def flags(self, index: QModelIndex): row = index.row() col = index.column() if row == 0: return Qt.ItemIsEnabled | Qt.ItemIsUserCheckable | \ Qt.ItemIsEditable else: if self._pair_info[self._data.columns[col]]['status']: if row == 1: # enable editing so that the combobox delegate can act return Qt.ItemIsEnabled | Qt.ItemIsEditable else: return Qt.ItemIsEnabled | Qt.ItemIsSelectable else: # disable all the data rows return ~Qt.ItemIsEnabled | Qt.ItemIsSelectable