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.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 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 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 getItem(self, index: QModelIndex) -> ProtocolTreeItem: if index.isValid(): item = index.internalPointer() if item: return item return self.rootItem
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 __newFolder(self): """ Private slot to add a new bookmarks folder. """ from .BookmarkNode import BookmarkNode currentIndex = self.bookmarksTree.currentIndex() idx = QModelIndex(currentIndex) sourceIndex = self.__proxyModel.mapToSource(idx) sourceNode = self.__bookmarksModel.node(sourceIndex) row = -1 # append new folder as the last item per default if sourceNode is not None and \ sourceNode.type() != BookmarkNode.Folder: # If the selected item is not a folder, add a new folder to the # parent folder, but directly below the selected item. idx = idx.parent() row = currentIndex.row() + 1 if not idx.isValid(): # Select bookmarks menu as default. idx = self.__proxyModel.index(1, 0) idx = self.__proxyModel.mapToSource(idx) parent = self.__bookmarksModel.node(idx) node = BookmarkNode(BookmarkNode.Folder) node.title = self.tr("New Folder") self.__bookmarksManager.addBookmark(parent, node, row)
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 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=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 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 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 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 rowCount(self, parent: QModelIndex = None, *args, **kwargs): if not self._root: return 0 if parent.isValid(): parentItem = parent.internalPointer() return parentItem.childrenCount() else: return self._root.childrenCount()
def parent(self, index: QtCore.QModelIndex): if not index.isValid(): return QtCore.QModelIndex() item = index.internalPointer().parent if item == self.root or item is None: return QtCore.QModelIndex() else: return self.createIndex(item.row, 0, item)
def setData(self, index: QModelIndex, value, role=Qt.DisplayRole): if role == Qt.CheckStateRole: proto_label = self.labels[index.row()] proto_label.fuzz_me = value self.protolabel_fuzzing_status_changed.emit(proto_label) elif role == Qt.EditRole: if len(value) > 0: self.labels[index.row()].name = value return True
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 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 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 parent(self, index: QModelIndex = None): if not index.isValid(): return QModelIndex() childItem = index.internalPointer() parentItem = childItem.parent if parentItem == self._root: return QModelIndex() else: return self.createIndex(parentItem.siblingNumber(), 0, parentItem)
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: QModelIndex, role=Qt.DisplayRole): i = index.row() participant = self.simulator_config.active_participants[i] if not index.isValid(): return None if role == Qt.DisplayRole: return participant.name + " (" + participant.shortname + ")" elif role == Qt.CheckStateRole: return Qt.Checked if participant.simulate else Qt.Unchecked
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 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 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 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 add_piece(self, name, data): # print(name, data) self.beginInsertRows(QModelIndex(), self.rowCount(), self.rowCount()) self._data_series.append(DataSerie(name, data)) self.endInsertRows()
def __init__(self, species=(), item=None, tax=True, last=0, index=QModelIndex(), count=0, length=0): """The constructor initializes the class NewVariantDialog.""" super().__init__() self.item = item self.value = None self.speciesRegistry = species.keys() self.species = -1 self.count = 0 self.tax = tax self.index = index # the last added index self.last = last self.count = count self.length = length self._OXYGEN_PATH_22 = os.path.join("resources", "icons", "oxygen", "22") self._LABEL_MIN_WIDTH = 240 self._piece_unit = " St." self._currency_unit = " " + self.locale().currencySymbol(QLocale.CurrencyIsoCode) self._currency_unit_piece = self._currency_unit + "/" + self._piece_unit.strip() self._spinbox_step = 0.05 self._COMBOBOX_ITEM_LIST = (QApplication.translate("VariantDataDialog", "Fence"), # Zaun QApplication.translate("VariantDataDialog", "Tree shelter")) # Wuchshülle # general things self.generalGroup = QGroupBox() self.variantInput = QComboBox() self.variantInput.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.Fixed) self.variantInput.addItems(self._COMBOBOX_ITEM_LIST) self.variantLabel = QLabel() self.variantLabel.setMinimumWidth(self._LABEL_MIN_WIDTH) self.variantLabel.setBuddy(self.variantInput) self.variantHint = ToolTipLabel() self.descriptionInput = QLineEdit() self.descriptionLabel = QLabel() self.descriptionLabel.setBuddy(self.descriptionInput) self.descriptionHint = ToolTipLabel() # create the layout of the general group box generalLayout = QGridLayout(self.generalGroup) generalLayout.setVerticalSpacing(15) generalLayout.addWidget(self.variantLabel, 0, 0, Qt.AlignTop) generalLayout.addWidget(self.variantInput, 0, 1, Qt.AlignTop) generalLayout.addWidget(self.variantHint, 0, 2, Qt.AlignTop) generalLayout.addWidget(self.descriptionLabel, 1, 0, Qt.AlignTop) generalLayout.addWidget(self.descriptionInput, 1, 1, Qt.AlignTop) generalLayout.addWidget(self.descriptionHint, 1, 2, Qt.AlignTop) # plant specific input fields self.plantGroup = QGroupBox() self.speciesInput = QComboBox() self.speciesInput.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.Fixed) self.speciesInput.addItems(library.TREESPECIES_DESCRIPTION) self.speciesLabel = QLabel() self.speciesLabel.setMinimumWidth(self._LABEL_MIN_WIDTH) self.speciesLabel.setBuddy(self.speciesInput) self.speciesHint = ToolTipLabel() self.speciesHint.hide() speciesSpacer = QSpacerItem(0, 30, QSizePolicy.Minimum, QSizePolicy.Fixed) self.speciesWarningSymbol = QLabel(pixmap=QPixmap(os.path.join(self._OXYGEN_PATH_22, "dialog-warning.png"))) self.speciesWarningSymbol.hide() self.speciesWarningText = QLabel(wordWrap=True) self.speciesWarningText.hide() warningLayout = QHBoxLayout() warningLayout.setContentsMargins(0, 0, 0, 0) warningLayout.addItem(speciesSpacer) warningLayout.addWidget(self.speciesWarningSymbol, alignment=Qt.AlignTop) warningLayout.addWidget(self.speciesWarningText, alignment=Qt.AlignTop) self.costInput = QDoubleSpinBox() self.costInput.setSuffix(self._currency_unit_piece) self.costInput.setSingleStep(self._spinbox_step) self.costLabel = QLabel() self.costLabel.setBuddy(self.costInput) self.costHint = ToolTipLabel() self.costHint.hide() self.costCalculator = QPushButton() self.preparationInput = QDoubleSpinBox() self.preparationInput.setSuffix(self._currency_unit_piece) self.preparationInput.setSingleStep(self._spinbox_step) self.preparationLabel = QLabel() self.preparationLabel.setBuddy(self.preparationInput) self.preparationHint = ToolTipLabel() self.preparationHint.hide() self.preparationCalculator = QPushButton() self.plantingInput = QDoubleSpinBox() self.plantingInput.setSuffix(self._currency_unit_piece) self.plantingInput.setSingleStep(self._spinbox_step) self.plantingLabel = QLabel() self.plantingLabel.setBuddy(self.plantingInput) self.plantingHint = ToolTipLabel() self.plantingHint.hide() self.plantingCalculator = QPushButton() self.tendingInput = QDoubleSpinBox() self.tendingInput.setSuffix(self._currency_unit_piece) self.tendingInput.setSingleStep(self._spinbox_step) self.tendingLabel = QLabel() self.tendingLabel.setBuddy(self.tendingInput) self.tendingHint = ToolTipLabel() self.tendingHint.hide() self.tendingCalculator = QPushButton() self.mortalityInput = QSpinBox() self.mortalityInput.setSuffix(" %") self.mortalityInput.setMaximum(100) self.mortalityInput.setValue(0) self.mortalityInput.setDisabled(True) self.mortalityLabel = QLabel() self.mortalityLabel.setBuddy(self.mortalityInput) self.mortalityHint = ToolTipLabel() self.mortalityHint.hide() # create the layout of the plant group box plantLayout = QGridLayout(self.plantGroup) plantLayout.addWidget(self.speciesLabel, 0, 0) plantLayout.addWidget(self.speciesInput, 0, 1) plantLayout.addWidget(self.speciesHint, 0, 2) plantLayout.addLayout(warningLayout, 1, 1) plantLayout.addWidget(self.costLabel, 2, 0) plantLayout.addWidget(self.costInput, 2, 1) plantLayout.addWidget(self.costHint, 2, 2) plantLayout.addWidget(self.costCalculator, 2, 3) plantLayout.addWidget(self.preparationLabel, 3, 0) plantLayout.addWidget(self.preparationInput, 3, 1) plantLayout.addWidget(self.preparationHint, 3, 2) plantLayout.addWidget(self.preparationCalculator, 3, 3) plantLayout.addWidget(self.plantingLabel, 4, 0) plantLayout.addWidget(self.plantingInput, 4, 1) plantLayout.addWidget(self.plantingHint, 4, 2) plantLayout.addWidget(self.plantingCalculator, 4, 3) plantLayout.addWidget(self.tendingLabel, 5, 0) plantLayout.addWidget(self.tendingInput, 5, 1) plantLayout.addWidget(self.tendingHint, 5, 2) plantLayout.addWidget(self.tendingCalculator, 5, 3) plantLayout.addWidget(self.mortalityLabel, 6, 0) plantLayout.addWidget(self.mortalityInput, 6, 1) plantLayout.addWidget(self.mortalityHint, 6, 2) # stacked widget for protection group self.fenceWidget = FenceInputWidget(self.tax) self.fenceWidget.length = self.length self.tubeWidget = TubeInputWidget(self.tax) self.protectionGroup = QStackedWidget() self.protectionGroup.addWidget(self.fenceWidget) self.protectionGroup.addWidget(self.tubeWidget) # sales tax hint taxLabel = QLabel("*) " + QApplication.translate("VariantDataDialog", # Bitte beachten Sie, dass Sie den Variantentyp später nicht mehr ändern können. "Keep in mind, that all values must contain uniformly " "the sales tax or not."), wordWrap=True) # create an ok button and abort button within a button box lineFrame = QFrame(frameShadow=QFrame.Sunken, frameShape=QFrame.VLine) self.buttonBox = QDialogButtonBox(QDialogButtonBox.Ok|QDialogButtonBox.Cancel|QDialogButtonBox.Help, orientation=Qt.Vertical) # create main layout dataLayout = QVBoxLayout() dataLayout.addWidget(self.generalGroup) dataLayout.addWidget(self.plantGroup) dataLayout.addWidget(self.protectionGroup) dataLayout.addWidget(taxLabel) dataLayout.addStretch() layout = QHBoxLayout(self) layout.addLayout(dataLayout) layout.addWidget(lineFrame) layout.addWidget(self.buttonBox) # connect actions self.variantInput.currentIndexChanged.connect(self.variantChanged) self.speciesInput.currentIndexChanged.connect(self.checkSpecies) self.buttonBox.accepted.connect(self.accept) self.buttonBox.rejected.connect(self.reject) self.buttonBox.helpRequested.connect(self.help) self.costCalculator.clicked.connect(self.costCalculation) self.preparationCalculator.clicked.connect(self.preparationCalculation) self.plantingCalculator.clicked.connect(self.plantingCalculation) self.tendingCalculator.clicked.connect(self.tendingCalculation) self.tubeWidget.countChanged.connect(self.updateCount) self.fenceWidget.lengthChanged.connect(self.updateLength) # update input fields if self.item: plant = self.item[TreeModel.PlantRole] protection = self.item[TreeModel.ProtectionRole] self.species = plant.species # update input fields self.variantInput.setCurrentIndex(protection.TYPE) self.variantInput.setDisabled(True) self.descriptionInput.setText(self.item[TreeModel.NameRole]) self.speciesInput.setCurrentIndex(plant.species) self.costInput.setValue(plant.cost) self.preparationInput.setValue(plant.preparation) self.plantingInput.setValue(plant.planting) self.tendingInput.setValue(plant.tending) self.mortalityInput.setValue(plant.mortality * 100) # update the protection group self.protectionGroup.currentWidget().setValues(protection) else: self.variantInput.setCurrentIndex(self.last) if self.index.isValid(): self.speciesInput.setCurrentIndex(self.index.data(TreeModel.SpeciesRole)) # check the species and show # a warning, if necessary self.checkSpecies() # translate the graphical user interface self.retranslateUi()
def insertRows(self, row, count, index=QModelIndex()): self.beginInsertRows(index, row, row + count - 1) for pos in range(row, row + count): self._data.insert(pos, '') self.endInsertRows() return True
def del_all(self): self.beginRemoveColumns(QModelIndex(), 0, self._row) self._data = [] self._row = 0 self._column = 0 self.endRemoveRows()
def addClient(self, client): row = len(self._clients) self.beginInsertRows(QModelIndex(), row, row) self._clients.append(ClientWrapper(client)) self.endInsertRows()
def fillRowerTable(self, out): self._data.clear() pieces = gd.sessionInfo['Pieces'] cntrating = [cr for nm, x, cr, tl in pieces] # target values targets = gd.globals['Boats'][gd.metaData['BoatType']] # First header line n = 1 series = DataSerie(n, ['', '2k Target', 'Average'] + gd.p_names) self.beginInsertRows(QModelIndex(), self.rowCount(), self.rowCount()) self._data.append(series) # how from self.rower to data? outboat = [d for d, e in out] # outboat[piece][rower] ri = [a[self.rower] for a in outboat] # rower info per piece # sp = [a['Split'] for a in outboat] # split per piece # the rest self._data.append( DataSerie(2, ['Stroke rate'] + [''] + [''] + [f'{r:.0f}' for c, r in cntrating])) """ self._data.append( DataSerie(2, ['' for i in range(len(gd.p_names)+3)]) ) """ avsplit = sum([d['Split'] for d, e in out]) / len(gd.p_names) self._data.append( DataSerie(2, ['500m split'] + [''] + [f'{int(avsplit/60)}:{avsplit%60:04.1f}'] + [ f'{int(d["Split"]/60)}:{d["Split"]%60:04.1f}' for d, e in out ])) targ = targets['angleIn'] avain = sum([r['CatchA'] for r in ri]) / len(gd.p_names) self._data.append( DataSerie(2, ['Catch angle (\u00b0)'] + [f'{targ:.0f}'] + [f'{avain:.0f}'] + [f'{r["CatchA"]:.0f}' for r in ri])) targ = targets['angleOut'] avaout = sum([r['FinA'] for r in ri]) / len(gd.p_names) self._data.append( DataSerie(2, ['Finish angle (\u00b0)'] + [f'{targ:.0f}'] + [f'{avaout:.0f}'] + [f'{r["FinA"]:.0f}' for r in ri])) targ = targets['angleOut'] - targets['angleIn'] avat = sum([r['FinA'] - r['CatchA'] for r in ri]) / len(gd.p_names) self._data.append( DataSerie(2, ['Total angle (\u00b0)'] + [f'{targ:.0f}'] + [f'{avat:.0f}'] + [f'{r["FinA"]-r["CatchA"]:.0f}' for r in ri])) targ = targets['slipIn'] aslip = sum([r['Slip'] for r in ri]) / len(gd.p_names) self._data.append( DataSerie(2, ['Catch slip (\u00b0) '] + [f'{targ:.0f}'] + [f'{aslip:.0f}'] + [f'{r["Slip"]:.0f}' for r in ri])) targ = targets['slipOut'] awash = sum([r['Wash'] for r in ri]) / len(gd.p_names) self._data.append( DataSerie(2, ['Finish wash (\u00b0) '] + [f'{targ:.0f}'] + [f'{awash:.0f}'] + [f'{r["Wash"]:.0f}' for r in ri])) targ = targets['angleOut'] - targets['angleIn'] - targets[ 'slipIn'] - targets['slipOut'] effan = sum([r['EffAngle'] for r in ri]) / len(gd.p_names) self._data.append( DataSerie(2, ['Effective angle (\u00b0)'] + [f'{targ:.0f}'] + [f'{effan:.0f}'] + [f'{r["EffAngle"]:.0f}' for r in ri])) self._data.append( DataSerie(2, ['Gate force max'] + [''] + [''] + [f'{r["GFMax"]:.0f}' for r in ri])) self._data.append( DataSerie(2, ['Gate force average'] + [''] + [''] + [f'{r["GFEff"]:.0f}' for r in ri])) """ self._data.append( DataSerie(2, ['Ratio avg/max Gate force'] + [''] + [''] + ['', '', '', '', '', '', '' , '' ])) self._data.append( DataSerie(2, ['Gate force max at'] + [''] + [''] + ['', '', '', '', '', '', '' , '' ])) self._data.append( DataSerie(2, ['Gate force up to 70% at (\u00b0)'] + [''] + [''] + [f'{r["UpAt70"]:.0f}' for r in ri])) self._data.append( DataSerie(2, ['Gate force under 70% at (\u00b0)'] + [''] + [''] + [f'{r["DownAt70"]:.0f}' for r in ri])) self._data.append( DataSerie(2, ['' for i in range(len(gd.p_names)+3)]) ) self._data.append( DataSerie(2, ['Work (J)'] + [''] + [''] + [f'{r["Work"]:.0f}' for r in ri])) """ targ = targets['power'] self._data.append( DataSerie(2, ['Power average (W)'] + [f'{targ:.0f}'] + [''] + [f'{r["PMean"]:.0f}' for r in ri])) self._data.append( DataSerie(2, ['Power/weight'] + [''] + [''] + [f'{r["PperKg"]:.2f}' for r in ri])) self._data.append( DataSerie(2, ['Progn Power target rate'] + ['' for i in range(len(gd.p_names) + 2)])) # power benen romp bankje? self.endInsertRows() self._column = len(self._data[0].data()) self._row = len(self._data)
def parent(self, index): """QAbstractItemModel method implementation """ return QModelIndex()
def setData(self, index: QModelIndex, value, role: int = ...) -> bool: try: self.base_model.get_result(index.row()).round_one_score = int(value) return True except ValueError: return False
def index(self, row, column, parent=QModelIndex()): return self.createIndex(row, column) if self.m_playlist is not None and not parent.isValid() and row >= 0 and row < self.m_playlist.mediaCount() and column >= 0 and column < self.ColumnCount else QModelIndex()
def columnCount(self, parent=QModelIndex()): return self.ColumnCount if not parent.isValid() else 0
def rowCount(self, parent=QModelIndex()): return self.m_playlist.mediaCount() if self.m_playlist is not None and not parent.isValid() else 0
def beginRemoveItems(self, start, end): self.beginRemoveRows(QModelIndex(), start, end)
def beginInsertItems(self, start, end): self.beginInsertRows(QModelIndex(), start, end)
def set_current_idx(self, set_current: QPersistentModelIndex): if set_current: assert isinstance(set_current, QPersistentModelIndex) assert set_current.isValid() self.selectionModel().select(QModelIndex(set_current), QItemSelectionModel.SelectCurrent)
def rowCount(self, parent=QModelIndex()): """Get count of active downloads.""" if parent.isValid(): # We don't have children return 0 return len(self.downloads)
def set_all(self, pieces): for (name, i, cr, tl) in pieces: self.beginInsertRows(QModelIndex(), self.rowCount(), self.rowCount()) self._data_series.append(DataSerie(name, i)) self.endInsertRows()
def rowCount(self, parent=QModelIndex()): return len(self._data)
def del_all(self): self.beginRemoveColumns(QModelIndex(), 0, len(self._data_series)) self._data_series = [] self.endRemoveRows()
def columnCount(self, parent=QModelIndex()): return len(self._df.columns)
def rowCount(self, parent=QModelIndex()): return self._row
def firstIndex(self): if len(self.widgets) == 0: return QModelIndex() return self.createIndex(0, 0)
def flags(self, index=QModelIndex()): return QAbstractItemModel.flags(self, index) | Qt.ItemIsEditable
def removeRows(self, row, count, index=QModelIndex()): self.beginRemoveRows(index, row, row + count - 1) for item in [self._data[i] for i in range(row, row + count)]: self._data.remove(item) self.endRemoveRows() return True
def add_row(self, vo: LabelVO): row = self._model.rowCount(QModelIndex()) self._model.insertRow(row) self._model.setData(self._model.index(row, 0), vo.name) self._model.setData(self._model.index(row, 1), vo.color) self._model.setData(self._model.index(row, 2), vo)
def del_piece(self, row): row = int(row) self.beginRemoveColumns(QModelIndex(), row, row) del self._data_series[row] self.endRemoveRows()
def new_item(self): print('Append new item') super().beginInsertRows(QModelIndex(), self.rowCount(), self.rowCount()) self._items.append(MyItem('new', self)) super().endInsertRows()
def add_data(self, data_series): self.beginInsertRows(QModelIndex(), self.rowCount(), self.rowCount()) self._data_series.append(data_series) self.endInsertRows()
def data(self, index: QModelIndex, role=None): if role == Qt.DisplayRole: value = self._data[index.row()][index.column()] return 'NULL' if value is None else str(value)
def parent(self, child): return QModelIndex()
def columnCount(self, parent=QModelIndex()): return self._column