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): 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 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 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 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 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 setData(self, index: QModelIndex, value, role=Qt.DisplayRole): if role == Qt.CheckStateRole: proto_label = self.message_type[index.row()] proto_label.show = value self.protolabel_visibility_changed.emit(proto_label) elif role == Qt.EditRole: proto_label = self.message_type[index.row()] proto_label.name = value self.message_type.change_field_type_of_label(proto_label, self.controller.field_types_by_caption.get(value, None)) self.protolabel_type_edited.emit() return True
def data(self, qModelIndex: QModelIndex, role = None): if not qModelIndex.row() >= 0: raise RuntimeError("row = {}".format(qModelIndex.row())) if role == TaskDataRole: result = self.adapterMap.at(qModelIndex.row()) return result elif role == Qt.DisplayRole: return self.data(qModelIndex, role = TaskDataRole).name elif role == CreationTimeRole: dt = QDateTime.fromTime_t( self.data(qModelIndex, role = TaskDataRole).creationTime) return dt elif role == TaskClassRole: return self.data(qModelIndex, TaskDataRole).klass
def setData(self, index: QModelIndex, value, role=None): if index.row() == 0 and role == Qt.CheckStateRole: if bool(value) != self.show_unassigned: self.show_unassigned = bool(value) self.show_state_changed.emit() elif role == Qt.CheckStateRole: try: if self.participants[index.row()-1].show != value: self.participants[index.row()-1].show = value self.show_state_changed.emit() except IndexError: return False return True
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, 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 data(self, index: QModelIndex, role: int = TAG_ROLE) -> str: row = self.languages[index.row()] if role == self.NAME_ROLE: return row[1] elif role == self.TAG_ROLE: return row[0] return ""
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 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 data(self, index: QModelIndex, role: int = NAME) -> Any: row = self.files[index.row()] if role == self.LOCAL_PARENT_PATH: return str(row["local_parent_path"]) elif role == self.LOCAL_PATH: return str(row["local_path"]) return row[self.names[role].decode()]
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 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 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 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: int = UID_ROLE) -> str: index = index.row() if index < 0 or index >= self.count: return "" uid = self.engines_uid[index] engine = self.application.manager._engines[uid] return getattr(engine, self.names[role].decode())
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 data(self, index: QModelIndex, role: int = None) -> QVariant: """ Return cell data for data table (str or numerical). :param index: QModelIndex with row number. :param role: int with column number + 32 (where user-space roles begins) :return: QVariant with the cell data (str / numerical) """ return str(self.my_data[index.row(), role - 32])
def setData(self, index: QModelIndex, value, role=None): i = index.row() participants = self.simulator_config.active_participants if role == Qt.CheckStateRole: participants[i].simulate = value self.update() self.participant_simulate_changed.emit(participants[i]) 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 edit_by_modelindex(self, index: QModelIndex, readonly: bool = None) -> None: if index is None: return if readonly is None: readonly = self.readonly model = self.model() item = model.listdata[index.row()] win = self.modal_dialog_class(self.session, item, readonly=readonly) win.edit_in_nested_transaction()
def data(self, index: QModelIndex, role: int = NAME) -> Any: row = self.actions[index.row()] if role == self.ID: return row["uid"] elif role == self.NAME: return row["name"] elif role == self.LAST_TRANSFER: return row["last_transfer"] elif role == self.PROGRESS: return row["progress"] return ""
def activateNext(self): """Select and activate next item If an item is selected in this LocationList, selects the next item and activates it. If no item was currently select, uses the first element. """ count = self.model().rowCount() if not count: return current = self.currentIndex() if not current.isValid(): current = QModelIndex(0, 0) elif current.row() < count - 1: current = current.sibling(current.row() + 1, 0) else: return self.setCurrentIndex(current) self.activated.emit(current)
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 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 row(self, index: QtCore.QModelIndex): if not index.isValid() or index.row() >= len( self.rest_data) or index.row() < 0: return None return self.rest_data[index.row()]
def flags(self, index: QModelIndex): if index.row() < len(self.vars): item = self.vars[index.row()] return super().flags(index) | (Qt.ItemIsEditable if hasattr( item.var, 'set') else 0) return super().flags(index)
def get_item(self, idx: QModelIndex) -> t.Optional[T]: try: return self._items[idx.row()] except IndexError: return None
def rowCount(self, parent: QModelIndex = QModelIndex()): sourceParent = self.mapToSource(parent).sibling(parent.row(), 0) return self.sourceModel().rowCount(sourceParent)
def exe_program(self, QModelIndex): self.program_index = QModelIndex.row() self.open_program()
def get_data_for_role(self, index: QModelIndex, role: Qt.ItemDataRole) -> QVariant: # note: this method is performance-critical. # it is called a lot, and so must run extremely fast. assert index.isValid() col = index.column() window = self.model.parent tx_item = self.get_data() is_lightning = tx_item.get('lightning', False) timestamp = tx_item['timestamp'] if is_lightning: status = 0 if timestamp is None: status_str = 'unconfirmed' else: status_str = format_time(int(timestamp)) else: tx_hash = tx_item['txid'] conf = tx_item['confirmations'] try: status, status_str = self.model.tx_status_cache[tx_hash] except KeyError: tx_mined_info = self.model.tx_mined_info_from_tx_item(tx_item) status, status_str = window.wallet.get_tx_status( tx_hash, tx_mined_info) if role == Qt.UserRole: # for sorting d = { HistoryColumns.STATUS: # respect sort order of self.transactions (wallet.get_full_history) -index.row(), HistoryColumns.DESCRIPTION: tx_item['label'] if 'label' in tx_item else None, HistoryColumns.AMOUNT: (tx_item['bc_value'].value if 'bc_value' in tx_item else 0)\ + (tx_item['ln_value'].value if 'ln_value' in tx_item else 0), HistoryColumns.BALANCE: (tx_item['balance'].value if 'balance' in tx_item else 0), HistoryColumns.FIAT_VALUE: tx_item['fiat_value'].value if 'fiat_value' in tx_item else None, HistoryColumns.FIAT_ACQ_PRICE: tx_item['acquisition_price'].value if 'acquisition_price' in tx_item else None, HistoryColumns.FIAT_CAP_GAINS: tx_item['capital_gain'].value if 'capital_gain' in tx_item else None, HistoryColumns.TXID: tx_hash if not is_lightning else None, } return QVariant(d[col]) if role not in (Qt.DisplayRole, Qt.EditRole): if col == HistoryColumns.STATUS and role == Qt.DecorationRole: icon = "lightning" if is_lightning else TX_ICONS[status] return QVariant(read_QIcon(icon)) elif col == HistoryColumns.STATUS and role == Qt.ToolTipRole: if is_lightning: msg = 'lightning transaction' else: # on-chain if tx_item['height'] == TX_HEIGHT_LOCAL: # note: should we also explain double-spends? msg = _( "This transaction is only available on your local machine.\n" "The currently connected server does not know about it.\n" "You can either broadcast it now, or simply remove it." ) else: msg = str(conf) + _(" confirmation" + ("s" if conf != 1 else "")) return QVariant(msg) elif col > HistoryColumns.DESCRIPTION and role == Qt.TextAlignmentRole: return QVariant(int(Qt.AlignRight | Qt.AlignVCenter)) elif col > HistoryColumns.DESCRIPTION and role == Qt.FontRole: monospace_font = QFont(MONOSPACE_FONT) return QVariant(monospace_font) #elif col == HistoryColumns.DESCRIPTION and role == Qt.DecorationRole and not is_lightning\ # and self.parent.wallet.invoices.paid.get(tx_hash): # return QVariant(read_QIcon("seal")) elif col in (HistoryColumns.DESCRIPTION, HistoryColumns.AMOUNT) \ and role == Qt.ForegroundRole and tx_item['value'].value < 0: red_brush = QBrush(QColor("#BC1E1E")) return QVariant(red_brush) elif col == HistoryColumns.FIAT_VALUE and role == Qt.ForegroundRole \ and not tx_item.get('fiat_default') and tx_item.get('fiat_value') is not None: blue_brush = QBrush(QColor("#1E1EFF")) return QVariant(blue_brush) return QVariant() if col == HistoryColumns.STATUS: return QVariant(status_str) elif col == HistoryColumns.DESCRIPTION and 'label' in tx_item: return QVariant(tx_item['label']) elif col == HistoryColumns.AMOUNT: bc_value = tx_item['bc_value'].value if 'bc_value' in tx_item else 0 ln_value = tx_item['ln_value'].value if 'ln_value' in tx_item else 0 value = bc_value + ln_value v_str = window.format_amount(value, is_diff=True, whitespaces=True) return QVariant(v_str) elif col == HistoryColumns.BALANCE: balance = tx_item['balance'].value balance_str = window.format_amount(balance, whitespaces=True) return QVariant(balance_str) elif col == HistoryColumns.FIAT_VALUE and 'fiat_value' in tx_item: value_str = window.fx.format_fiat(tx_item['fiat_value'].value) return QVariant(value_str) elif col == HistoryColumns.FIAT_ACQ_PRICE and \ tx_item['value'].value < 0 and 'acquisition_price' in tx_item: # fixme: should use is_mine acq = tx_item['acquisition_price'].value return QVariant(window.fx.format_fiat(acq)) elif col == HistoryColumns.FIAT_CAP_GAINS and 'capital_gain' in tx_item: cg = tx_item['capital_gain'].value return QVariant(window.fx.format_fiat(cg)) elif col == HistoryColumns.TXID: return QVariant(tx_hash) if not is_lightning else QVariant('') return QVariant()
def stack_changer(self, index: QModelIndex): self.dialog.views.setCurrentIndex(index.row()) print(self.dialog.views.currentWidget().objectName()) for i in self.enabledWidgetsChanger: i()
def data(self, index: QtCore.QModelIndex, role: int = ...): if not index.isValid(): return QtCore.QVariant() elif role != QtCore.Qt.DisplayRole: return QtCore.QVariant() return QtCore.QVariant(self.arraydata[index.row()][index.column()])
def data(self, index: QModelIndex, role: int = ...) -> typing.Any: if role == Qt.DisplayRole: return self._data[index.row()][index.column()] elif role == Qt.ToolTipRole: return f"{self._data[index.row()][3]}"
def editActor(self, idx: qc.QModelIndex) -> None: dialog = ActorEditDialog(self, self.flow_data, idx.row()) dialog.exec_()
def setCurrentMerge(self, idx: QModelIndex = QModelIndex()): sourceIndex = self.sourceModel().index(idx.row(), idx.column()) self.sourceModel().setCurrentMerge(sourceIndex)
def mapFromSource(self, sourceIdx: QModelIndex = QModelIndex()): if not sourceIdx.isValid(): return QModelIndex() return self.index(sourceIdx.row(), Column.PluginName)
def mapFromSource(self, sourceIdx: QModelIndex): # source index is for the PluginModel, # maps to a depth 0 row if not sourceIdx.isValid(): return QModelIndex() return self.index(sourceIdx.row(), Column.PluginName)
def data(self, index: QModelIndex, role=None): if not index.isValid(): return QVariant() row = index.row() col = index.column() item: TaskItem = self._modelDomain.taskList[row] if role == Qt.DisplayRole or role == Qt.ToolTipRole: if col == self.ColumnIndex: return QVariant(str(row + 1).zfill(4) + " id=" + str(item.item_id)) elif col == self.ColumnProject: if not item.item_projectId: return QVariant("ERROR") return QVariant(self._modelDomain.dicts[const.DICT_PROJECT].getData(item.item_projectId)) elif col == self.ColumnInitiator: if not item.item_initiatorId: return QVariant("ERROR") return QVariant(self._modelDomain.dicts[const.DICT_INITIATOR].getData(item.item_initiatorId)) elif col == self.ColumnDescription: return QVariant(item.item_description) elif col == self.ColumnUser: return QVariant(self._modelDomain.dicts[const.DICT_USER].getData(item.item_userId)) elif col == self.ColumnPercent: return QVariant(str(item.item_percent) + "%") elif col == self.ColumnDateBegin: return QVariant(str(item.item_dateBegin)) # TODO: check dates for nulls elif col == self.ColumnDateChange: return QVariant(str(item.item_dateChange)) elif col == self.ColumnDateEnd: return QVariant(str(item.item_dateEnd)) elif col == self.ColumnDifficulty: return QVariant(str(item.item_difficulty) + "/10") # elif col == self.ColumnActive: # return QVariant(str((2 - item.item_active) * 2)) # TODO: rework active column: 0 = no, 2 = yes elif col == self.ColumnPriority: if not item.item_priorityId: return QVariant("ERROR") return QVariant(self._modelDomain.dicts[const.DICT_PRIORITY].getData(item.item_priorityId)) return QVariant() elif role == Qt.CheckStateRole: if col == self.ColumnActive: return QVariant(item.item_active) elif role == Qt.BackgroundRole: if item.item_percent == 100: return QVariant(QBrush(QColor(const.COLOR_PERCENT_100))) # TODO: make added task highlight elif col == self.ColumnDescription: if item.item_strict == 1: return QVariant(QBrush(QColor(const.COLOR_STRICT_DATE))) elif col == self.ColumnPriority: if item.item_priorityId == 1: return QVariant(QBrush(QColor(const.COLOR_PRIORITY_HIGH))) if item.item_priorityId == 2: return QVariant(QBrush(QColor(const.COLOR_PRIORITY_MEDIUM))) if item.item_priorityId == 3: return QVariant(QBrush(QColor(const.COLOR_PRIORITY_LOW))) elif col == self.ColumnDateEnd: if not item.item_dateEnd: return QVariant() days = (item.item_dateEnd - datetime.date.today()).days if days <= 0: return QVariant(QBrush(QColor(const.COLOR_DEADLINE_HIGH))) elif days in range(1, 8): return QVariant(QBrush(QColor(const.COLOR_DEADLINE_MEDIUM))) elif days > 7: return QVariant(QBrush(QColor(const.COLOR_DEADLINE_LOW))) # retcolor = Qt.white; # # if item.item_status == 1: # retcolor = const.COLOR_PAYMENT_FINISHED # # if col == self.ColumnStatus: # if item.item_status == 2: # retcolor = const.COLOR_PAYMENT_PENDING # if col == self.ColumnPriority: # if item.item_status != 1: # if item.item_priority == 2: # 3 4 # retcolor = const.COLOR_PRIORITY_LOW # elif item.item_priority == 3: # retcolor = const.COLOR_PRIORITY_MEDIUM # elif item.item_priority == 4: # retcolor = const.COLOR_PRIORITY_HIGH # if col == self.ColumnShipmentStatus: # if item.item_shipment_status == 2: # retcolor = const.COLOR_ARRIVAL_PENDING # if item.item_shipment_status == 3: # retcolor = const.COLOR_ARRIVAL_PARTIAL # if item.item_shipment_status == 4: # retcolor = const.COLOR_ARRIVAL_RECLAIM # return QVariant(QBrush(QColor(retcolor))) elif role == const.RoleNodeId: return item.item_id elif role == const.RoleUser: return item.item_userId elif role == const.RoleInit: return item.item_initiatorId elif role == const.RoleProject: return item.item_projectId elif role == const.RoleDateBegin: return item.item_dateBegin elif role == const.RoleDateEnd: return item.item_dateEnd elif role == const.RoleActive: return item.item_active elif role == const.RoleStrict: return item.item_strict elif role == const.RolePercent: return item.item_percent elif role == const.RoleFilterData: return item.item_id, item.item_userId, item.item_initiatorId, item.item_projectId, item.item_dateBegin, \ item.item_dateEnd, item.item_active, item.item_strict, item.item_percent elif role == const.RoleNote: return item.item_note return QVariant()
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 isinstance(lbl, ChecksumLabel) and self.message is not None: 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.color_index elif j == 2: return lbl.DISPLAY_FORMATS[lbl.display_format_index] elif j == 3: return lbl.display_order_str elif j == 4: return self.__display_data(lbl, calculated_crc) elif role == Qt.CheckStateRole and j == 0: return lbl.show elif role == Qt.BackgroundColorRole: if isinstance( lbl, ChecksumLabel) and j == 4 and self.message is not None: 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 elif role == Qt.ToolTipRole: if j == 2: return self.tr( "Choose display type for the value of the label:" "<ul>" "<li>Bit</li>" "<li>Hexadecimal (Hex)</li>" "<li>ASCII chars</li>" "<li>Decimal Number</li>" "<li>Binary Coded Decimal (BCD)</li>" "</ul>") if j == 3: return self.tr("Choose bit order for the displayed value:" "<ul>" "<li>Most Significant Bit (MSB) [Default]</li>" "<li>Least Significant Bit (LSB)</li>" "<li>Least Significant Digit (LSD)</li>" "</ul>") elif role == Qt.FontRole and j == 0: font = QFont() font.setBold(i in self.selected_label_indices) return font
def table_clicked(self, index): index = QModelIndex(index) # ind.__setattr__('column',0) row, col = index.row(), index.column() ind = self.model.index(row, 2) image = list(self.model.itemData(QModelIndex(ind)).values())[0] ind = self.model.index(row, 3) yxMax = list(self.model.itemData(QModelIndex(ind)).values())[0] yxMax = yxMax.replace('[', '').replace(']', '').split() yxMax = [int(float(i)) for i in yxMax] yxMax = [tuple(yxMax[i + 0:2 + i]) for i in range(0, len(yxMax), 2)] ind = self.model.index(row, 4) yxMin = list(self.model.itemData(QModelIndex(ind)).values())[0] yxMin = yxMin.replace('[', '').replace(']', '').split() yxMin = [int(float(i)) for i in yxMin] yxMin = [tuple(yxMin[i + 0:2 + i]) for i in range(0, len(yxMin), 2)] ind = self.model.index(row, 7) center = list(self.model.itemData(QModelIndex(ind)).values())[0] center = center.replace('[', '').replace(']', '').split() center = [int(float(i)) for i in center] center = [tuple(center[i + 0:2 + i]) for i in range(0, len(center), 2)] # print(center) classes = self.config['dataset']['category'].split(',') ind = self.model.index(row, 0) label = list(self.model.itemData(QModelIndex(ind)).values())[0] label = label.replace('[', '').replace(']', '').split() # yxMin=ast.literal_eval(yxMin.replace(' ', ',')) classes = self.config['dataset']['category'].split(',') name = str(image.split('\\')[-1]) image = cv2.imread(image) objs = [] for i in range(len(yxMax)): y1, x1 = yxMin[i] y2, x2 = yxMax[i] # # # print(i,'value: ',x1, y1 ,x2, y2 ) # # start_point = (x1, y1) end_point = (x2, y2) color = (255, 0, 0) thickness = 2 objs.append("{}-{}".format(i + 1, classes[int(label[i])])) cv2.putText( image, '{}-{}({})'.format(i + 1, classes[int(label[i])], label[i]), (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.3, (0, 0, 255), 1) image = cv2.rectangle(image, start_point, end_point, color, thickness) image = cv2.circle(image, (center[i][1], center[i][0]), 2, (0, 0, 255), -1) # util.Qlogging(self.ui.textBrowser, '{} has {} objects: \\n {}'.format(name,len(yxMax),objs),'red' ) cv2.imshow(name, image) cv2.waitKey(4000) cv2.destroyAllWindows()
def found_table_double_clicked(self, index: QModelIndex): if not index.isValid(): return clicked_value = self.found_table.model().get_value(index.row()) self.saved_results.model().append_row(clicked_value)
def mapToSource(self, index: QtCore.QModelIndex) -> QtCore.QModelIndex: return self.__registry.index(index.row(), index.column(), self.__root)
def data(self, index: QModelIndex, role: int): if role == Qt.DisplayRole: if index.column() == 0: return self.canvas_name[index.row()] elif index.column() == 1: return "O" if self.is_visible[index.row()] else "X"
def mapFromSource(self, index: QtCore.QModelIndex) -> QtCore.QModelIndex: if not index.isValid(): return QtCore.QModelIndex() return self.createIndex(index.row(), index.column(), QtCore.QModelIndex())
def mapFromSource(self, sourceIdx: QModelIndex = QModelIndex()): if not sourceIdx.isValid(): return QModelIndex() return self.createIndex( sourceIdx.row(), self.sourceColumnToProxy(sourceIdx.column()), sourceIdx.internalPointer(), )
def slot_clicked_item(self, QModelIndex): self.stk_w.setCurrentIndex(QModelIndex.row()) self.program_index = QModelIndex.row()
def data(self, index: QModelIndex, role=None): if not index.isValid(): return QVariant() elif role != Qt.DisplayRole and role != Qt.EditRole: return QVariant() return QVariant(getattr(self.array_data[index.row()], self.header_data[index.column()]))
def data(self, index: QModelIndex, role: Qt.ItemDataRole) -> QVariant: # note: this method is performance-critical. # it is called a lot, and so must run extremely fast. assert index.isValid() col = index.column() tx_item = self.transactions.value_from_pos(index.row()) is_lightning = tx_item.get('lightning', False) timestamp = tx_item['timestamp'] if is_lightning: status = 0 txpos = tx_item['txpos'] if timestamp is None: status_str = 'unconfirmed' else: status_str = format_time(int(timestamp)) else: tx_hash = tx_item['txid'] conf = tx_item['confirmations'] txpos = tx_item['txpos_in_block'] or 0 height = tx_item['height'] try: status, status_str = self.tx_status_cache[tx_hash] except KeyError: tx_mined_info = self.tx_mined_info_from_tx_item(tx_item) status, status_str = self.parent.wallet.get_tx_status( tx_hash, tx_mined_info) # we sort by timestamp if timestamp is None: timestamp = float("inf") if role == Qt.UserRole: # for sorting d = { HistoryColumns.STATUS: # height breaks ties for unverified txns # txpos breaks ties for verified same block txns (-timestamp, conf, -status, -height, -txpos) if not is_lightning else (-timestamp, 0,0,0,-txpos), HistoryColumns.DESCRIPTION: tx_item['label'] if 'label' in tx_item else None, HistoryColumns.AMOUNT: (tx_item['bc_value'].value if 'bc_value' in tx_item else 0)\ + (tx_item['ln_value'].value if 'ln_value' in tx_item else 0), HistoryColumns.BALANCE: (tx_item['balance'].value if 'balance' in tx_item else 0)\ + (tx_item['balance_msat']//1000 if 'balance_msat'in tx_item else 0), HistoryColumns.FIAT_VALUE: tx_item['fiat_value'].value if 'fiat_value' in tx_item else None, HistoryColumns.FIAT_ACQ_PRICE: tx_item['acquisition_price'].value if 'acquisition_price' in tx_item else None, HistoryColumns.FIAT_CAP_GAINS: tx_item['capital_gain'].value if 'capital_gain' in tx_item else None, HistoryColumns.TXID: tx_hash if not is_lightning else None, } return QVariant(d[col]) if role not in (Qt.DisplayRole, Qt.EditRole): if col == HistoryColumns.STATUS and role == Qt.DecorationRole: icon = "lightning" if is_lightning else TX_ICONS[status] return QVariant(read_QIcon(icon)) elif col == HistoryColumns.STATUS and role == Qt.ToolTipRole: msg = 'lightning transaction' if is_lightning else str( conf) + _(" confirmation" + ("s" if conf != 1 else "")) return QVariant(msg) elif col > HistoryColumns.DESCRIPTION and role == Qt.TextAlignmentRole: return QVariant(Qt.AlignRight | Qt.AlignVCenter) elif col != HistoryColumns.STATUS and role == Qt.FontRole: monospace_font = QFont(MONOSPACE_FONT) return QVariant(monospace_font) #elif col == HistoryColumns.DESCRIPTION and role == Qt.DecorationRole and not is_lightning\ # and self.parent.wallet.invoices.paid.get(tx_hash): # return QVariant(read_QIcon("seal")) elif col in (HistoryColumns.DESCRIPTION, HistoryColumns.AMOUNT) \ and role == Qt.ForegroundRole and tx_item['value'].value < 0: red_brush = QBrush(QColor("#BC1E1E")) return QVariant(red_brush) elif col == HistoryColumns.FIAT_VALUE and role == Qt.ForegroundRole \ and not tx_item.get('fiat_default') and tx_item.get('fiat_value') is not None: blue_brush = QBrush(QColor("#1E1EFF")) return QVariant(blue_brush) return QVariant() if col == HistoryColumns.STATUS: return QVariant(status_str) elif col == HistoryColumns.DESCRIPTION and 'label' in tx_item: return QVariant(tx_item['label']) elif col == HistoryColumns.AMOUNT: bc_value = tx_item['bc_value'].value if 'bc_value' in tx_item else 0 ln_value = tx_item['ln_value'].value if 'ln_value' in tx_item else 0 value = bc_value + ln_value v_str = self.parent.format_amount(value, is_diff=True, whitespaces=True) return QVariant(v_str) elif col == HistoryColumns.BALANCE: balance = tx_item['balance'].value balance_str = self.parent.format_amount(balance, whitespaces=True) return QVariant(balance_str) elif col == HistoryColumns.FIAT_VALUE and 'fiat_value' in tx_item: value_str = self.parent.fx.format_fiat(tx_item['fiat_value'].value) return QVariant(value_str) elif col == HistoryColumns.FIAT_ACQ_PRICE and \ tx_item['value'].value < 0 and 'acquisition_price' in tx_item: # fixme: should use is_mine acq = tx_item['acquisition_price'].value return QVariant(self.parent.fx.format_fiat(acq)) elif col == HistoryColumns.FIAT_CAP_GAINS and 'capital_gain' in tx_item: cg = tx_item['capital_gain'].value return QVariant(self.parent.fx.format_fiat(cg)) elif col == HistoryColumns.TXID: return QVariant(tx_hash) if not is_lightning else QVariant('') return QVariant()
class textEditView(QTextEdit): def __init__(self, parent=None, index=None, html=None, spellcheck=True, highlighting=False, dict="", autoResize=False): QTextEdit.__init__(self, parent) self._column = Outline.text self._index = None self._indexes = None self._model = None self._placeholderText = self.placeholderText() self._updating = False self._item = None self._highlighting = highlighting self._textFormat = "text" self.setAcceptRichText(False) # When setting up a theme, this becomes true. self._fromTheme = False self._themeData = None self._highlighterClass = BasicHighlighter self.spellcheck = spellcheck self.currentDict = dict if dict else settings.dict self._defaultFontSize = qApp.font().pointSize() self.highlighter = None self.setAutoResize(autoResize) self._defaultBlockFormat = QTextBlockFormat() self._defaultCharFormat = QTextCharFormat() self.highlightWord = "" self.highligtCS = False self._dict = None # self.document().contentsChanged.connect(self.submit, F.AUC) # Submit text changed only after 500ms without modifications self.updateTimer = QTimer() self.updateTimer.setInterval(500) self.updateTimer.setSingleShot(True) self.updateTimer.timeout.connect(self.submit) # self.updateTimer.timeout.connect(lambda: print("Timeout")) self.updateTimer.stop() self.document().contentsChanged.connect(self.updateTimer.start, F.AUC) # self.document().contentsChanged.connect(lambda: print("Document changed")) # self.document().contentsChanged.connect(lambda: print(self.objectName(), "Contents changed")) self.setEnabled(False) if index: self.setCurrentModelIndex(index) elif html: self.document().setHtml(html) self.setReadOnly(True) # Spellchecking if enchant and self.spellcheck: try: self._dict = enchant.Dict(self.currentDict if self.currentDict else self.getDefaultLocale()) except enchant.errors.DictNotFoundError: self.spellcheck = False else: self.spellcheck = False if self._highlighting and not self.highlighter: self.highlighter = self._highlighterClass(self) self.highlighter.setDefaultBlockFormat(self._defaultBlockFormat) def getDefaultLocale(self): default_locale = enchant.get_default_language() if default_locale is None: default_locale = QLocale.system().name() if default_locale is None: default_locale = enchant.list_dicts()[0][0] return default_locale def setModel(self, model): self._model = model try: self._model.dataChanged.connect(self.update, F.AUC) except TypeError: pass def setColumn(self, col): self._column = col def setHighlighting(self, val): self._highlighting = val def setDefaultBlockFormat(self, bf): self._defaultBlockFormat = bf if self.highlighter: self.highlighter.setDefaultBlockFormat(bf) def setCurrentModelIndex(self, index): self._indexes = None if index.isValid(): self.setEnabled(True) if index.column() != self._column: index = index.sibling(index.row(), self._column) self._index = QPersistentModelIndex(index) self.setPlaceholderText(self._placeholderText) if not self._model: self.setModel(index.model()) self.setupEditorForIndex(self._index) self.loadFontSettings() self.updateText() else: self._index = QModelIndex() self.setPlainText("") self.setEnabled(False) def currentIndex(self): """ Getter function used to normalized views access with QAbstractItemViews. """ if self._index: return self._index else: return QModelIndex() def getSelection(self): """ Getter function used to normalized views access with QAbstractItemViews. """ return [self.currentIndex()] def setCurrentModelIndexes(self, indexes): self._index = None self._indexes = [] for i in indexes: if i.isValid(): self.setEnabled(True) if i.column() != self._column: i = i.sibling(i.row(), self._column) self._indexes.append(QModelIndex(i)) if not self._model: self.setModel(i.model()) self.updateText() def setupEditorForIndex(self, index): # Setting highlighter if self._highlighting: self.highlighter = self._highlighterClass(self) self.highlighter.setDefaultBlockFormat(self._defaultBlockFormat) self.highlighter.updateColorScheme() def loadFontSettings(self): if self._fromTheme or \ not self._index or \ type(self._index.model()) != outlineModel or \ self._column != Outline.text: return opt = settings.textEditor f = QFont() f.fromString(opt["font"]) background = (opt["background"] if not opt["backgroundTransparent"] else "transparent") foreground = opt["fontColor"] # if not opt["backgroundTransparent"] # else S.text # self.setFont(f) self.setStyleSheet("""QTextEdit{{ background: {bg}; color: {foreground}; font-family: {ff}; font-size: {fs}; margin: {mTB}px {mLR}px; {maxWidth} }} """.format( bg=background, foreground=foreground, ff=f.family(), fs="{}pt".format(str(f.pointSize())), mTB = opt["marginsTB"], mLR = opt["marginsLR"], maxWidth = "max-width: {}px;".format(opt["maxWidth"]) if opt["maxWidth"] else "", ) ) self._defaultFontSize = f.pointSize() # We set the parent background to the editor's background in case # there are margins. We check that the parent class is a QWidget because # if textEditView is used in fullScreenEditor, then we don't want to # set the background. if self.parent().__class__ == QWidget: self.parent().setStyleSheet(""" QWidget#{name}{{ background: {bg}; }}""".format( # We style by name, otherwise all inheriting widgets get the same # colored background, for example context menu. name=self.parent().objectName(), bg=background, )) cf = QTextCharFormat() # cf.setFont(f) # cf.setForeground(QColor(opt["fontColor"])) self.setCursorWidth(opt["cursorWidth"]) bf = QTextBlockFormat() bf.setLineHeight(opt["lineSpacing"], bf.ProportionalHeight) bf.setTextIndent(opt["tabWidth"] * 1 if opt["indent"] else 0) bf.setTopMargin(opt["spacingAbove"]) bf.setBottomMargin(opt["spacingBelow"]) bf.setAlignment(Qt.AlignLeft if opt["textAlignment"] == 0 else Qt.AlignCenter if opt["textAlignment"] == 1 else Qt.AlignRight if opt["textAlignment"] == 2 else Qt.AlignJustify) self._defaultCharFormat = cf self._defaultBlockFormat = bf if self.highlighter: self.highlighter.updateColorScheme() self.highlighter.setMisspelledColor(QColor(opt["misspelled"])) self.highlighter.setDefaultCharFormat(self._defaultCharFormat) self.highlighter.setDefaultBlockFormat(self._defaultBlockFormat) def update(self, topLeft, bottomRight): if self._updating: return if self._index and self._index.isValid(): if topLeft.parent() != self._index.parent(): return # print("Model changed: ({}:{}), ({}:{}/{}), ({}:{}) for {} of {}".format( # topLeft.row(), topLeft.column(), # self._index.row(), self._index.row(), self._column, # bottomRight.row(), bottomRight.column(), # self.objectName(), self.parent().objectName())) if topLeft.row() <= self._index.row() <= bottomRight.row(): if topLeft.column() <= self._column <= bottomRight.column(): self.updateText() elif self._indexes: update = False for i in self._indexes: if topLeft.row() <= i.row() <= bottomRight.row(): update = True if update: self.updateText() def disconnectDocument(self): try: self.document().contentsChanged.disconnect(self.updateTimer.start) except: pass def reconnectDocument(self): self.document().contentsChanged.connect(self.updateTimer.start, F.AUC) def updateText(self): if self._updating: return # print("Updating", self.objectName()) self._updating = True if self._index: self.disconnectDocument() if self.toPlainText() != F.toString(self._index.data()): # print(" Updating plaintext") self.document().setPlainText(F.toString(self._index.data())) self.reconnectDocument() elif self._indexes: self.disconnectDocument() t = [] same = True for i in self._indexes: item = i.internalPointer() t.append(F.toString(item.data(self._column))) for t2 in t[1:]: if t2 != t[0]: same = False break if same: self.document().setPlainText(t[0]) else: self.document().setPlainText("") if not self._placeholderText: self._placeholderText = self.placeholderText() self.setPlaceholderText(self.tr("Various")) self.reconnectDocument() self._updating = False def submit(self): self.updateTimer.stop() if self._updating: return # print("Submitting", self.objectName()) if self._index and self._index.isValid(): # item = self._index.internalPointer() if self.toPlainText() != self._index.data(): # print(" Submitting plain text") self._updating = True self._model.setData(QModelIndex(self._index), self.toPlainText()) self._updating = False elif self._indexes: self._updating = True for i in self._indexes: item = i.internalPointer() if self.toPlainText() != F.toString(item.data(self._column)): print("Submitting many indexes") self._model.setData(i, self.toPlainText()) self._updating = False def keyPressEvent(self, event): if event.key() == Qt.Key_V and event.modifiers() & Qt.ControlModifier: text = QApplication.clipboard().text() self.insertPlainText(text) else: QTextEdit.keyPressEvent(self, event) if event.key() == Qt.Key_Space: self.submit() # ----------------------------------------------------------------------------------------------------- # Resize stuff def resizeEvent(self, e): QTextEdit.resizeEvent(self, e) if self._autoResize: self.sizeChange() def sizeChange(self): opt = settings.textEditor docHeight = self.document().size().height() + 2 * opt["marginsTB"] if self.heightMin <= docHeight <= self.heightMax: self.setMinimumHeight(docHeight) def setAutoResize(self, val): self._autoResize = val if self._autoResize: self.document().contentsChanged.connect(self.sizeChange) self.heightMin = 0 self.heightMax = 65000 self.sizeChange() ############################################################################### # SPELLCHECKING ############################################################################### # Based on http://john.nachtimwald.com/2009/08/22/qplaintextedit-with-in-line-spell-check/ def setDict(self, d): self.currentDict = d if d and enchant.dict_exists(d): self._dict = enchant.Dict(d) if self.highlighter: self.highlighter.rehighlight() def toggleSpellcheck(self, v): self.spellcheck = v if enchant and self.spellcheck and not self._dict: if self.currentDict and enchant.dict_exists(self.currentDict): self._dict = enchant.Dict(self.currentDict) elif enchant.get_default_language() and enchant.dict_exists(enchant.get_default_language()): self._dict = enchant.Dict(enchant.get_default_language()) else: self.spellcheck = False if self.highlighter: self.highlighter.rehighlight() else: self.spellcheck = False def mousePressEvent(self, event): if event.button() == Qt.RightButton: # Rewrite the mouse event to a left button event so the cursor is # moved to the location of the pointer. event = QMouseEvent(QEvent.MouseButtonPress, event.pos(), Qt.LeftButton, Qt.LeftButton, Qt.NoModifier) QTextEdit.mousePressEvent(self, event) def wheelEvent(self, event): """ We catch wheelEvent if key modifier is CTRL to change font size. Note: this should be in a class specific for main textEditView (#TODO). """ if event.modifiers() & Qt.ControlModifier: # Get the wheel angle. d = event.angleDelta().y() / 120 # Update settings f = QFont() f.fromString(settings.textEditor["font"]) f.setPointSizeF(f.pointSizeF() + d) settings.textEditor["font"] = f.toString() # Update font to all textEditView. Drastically. for w in F.mainWindow().findChildren(textEditView, QRegExp(".*")): w.loadFontSettings() # We tell the world that we accepted this event event.accept() return QTextEdit.wheelEvent(self, event) class SpellAction(QAction): """A special QAction that returns the text in a signal. Used for spellcheck.""" correct = pyqtSignal(str) def __init__(self, *args): QAction.__init__(self, *args) self.triggered.connect(lambda x: self.correct.emit( str(self.text()))) def contextMenuEvent(self, event): # Based on http://john.nachtimwald.com/2009/08/22/qplaintextedit-with-in-line-spell-check/ popup_menu = self.createStandardContextMenu() popup_menu.exec_(event.globalPos()) def createStandardContextMenu(self): popup_menu = QTextEdit.createStandardContextMenu(self) if not self.spellcheck: return popup_menu # Select the word under the cursor. # But only if there is no selection (otherwise it's impossible to select more text to copy/cut) cursor = self.textCursor() if not cursor.hasSelection(): cursor.select(QTextCursor.WordUnderCursor) self.setTextCursor(cursor) # Check if the selected word is misspelled and offer spelling # suggestions if it is. if cursor.hasSelection(): text = str(cursor.selectedText()) valid = self._dict.check(text) selectedWord = cursor.selectedText() if not valid: spell_menu = QMenu(self.tr('Spelling Suggestions'), self) spell_menu.setIcon(F.themeIcon("spelling")) for word in self._dict.suggest(text): action = self.SpellAction(word, spell_menu) action.correct.connect(self.correctWord) spell_menu.addAction(action) # Only add the spelling suggests to the menu if there are # suggestions. if len(spell_menu.actions()) != 0: popup_menu.insertSeparator(popup_menu.actions()[0]) # Adds: add to dictionary addAction = QAction(self.tr("&Add to dictionary"), popup_menu) addAction.setIcon(QIcon.fromTheme("list-add")) addAction.triggered.connect(self.addWordToDict) addAction.setData(selectedWord) popup_menu.insertAction(popup_menu.actions()[0], addAction) # Adds: suggestions popup_menu.insertMenu(popup_menu.actions()[0], spell_menu) # popup_menu.insertSeparator(popup_menu.actions()[0]) # If word was added to custom dict, give the possibility to remove it elif valid and self._dict.is_added(selectedWord): popup_menu.insertSeparator(popup_menu.actions()[0]) # Adds: remove from dictionary rmAction = QAction(self.tr("&Remove from custom dictionary"), popup_menu) rmAction.setIcon(QIcon.fromTheme("list-remove")) rmAction.triggered.connect(self.rmWordFromDict) rmAction.setData(selectedWord) popup_menu.insertAction(popup_menu.actions()[0], rmAction) return popup_menu def correctWord(self, word): """ Replaces the selected text with word. """ cursor = self.textCursor() cursor.beginEditBlock() cursor.removeSelectedText() cursor.insertText(word) cursor.endEditBlock() def addWordToDict(self): word = self.sender().data() self._dict.add(word) self.highlighter.rehighlight() def rmWordFromDict(self): word = self.sender().data() self._dict.remove(word) self.highlighter.rehighlight() ############################################################################### # FORMATTING ############################################################################### def focusOutEvent(self, event): """Submit changes just before focusing out.""" QTextEdit.focusOutEvent(self, event) self.submit() ############################################################################### # KEYBOARD SHORTCUTS ############################################################################### def callMainTreeView(self, functionName): """ The tree view in main window must have same index as the text edit that has focus. So we can pass it the call for documents edits like: duplicate, move up, etc. """ if self._index and self._column == Outline.text: function = getattr(F.mainWindow().treeRedacOutline, functionName) function() def rename(self): self.callMainTreeView("rename") def duplicate(self): self.callMainTreeView("duplicate") def moveUp(self): self.callMainTreeView("moveUp") def moveDown(self): self.callMainTreeView("moveDown")
def onCollapsed(self, idx: QModelIndex): idx = self.infoModel().mapToSource(idx) self.expandedRows[idx.row()] = False
def data(self, index: QModelIndex, role: Qt.ItemDataRole) -> QVariant: # note: this method is performance-critical. # it is called a lot, and so must run extremely fast. assert index.isValid() col = index.column() tx_item = self.transactions.value_from_pos(index.row()) tx_hash = tx_item['txid'] conf = tx_item['confirmations'] txpos = tx_item['txpos_in_block'] or 0 height = tx_item['height'] try: status, status_str = self.tx_status_cache[tx_hash] except KeyError: tx_mined_info = self.tx_mined_info_from_tx_item(tx_item) status, status_str = self.parent.wallet.get_tx_status( tx_hash, tx_mined_info) if role == Qt.UserRole: # for sorting d = { HistoryColumns.STATUS_ICON: # height breaks ties for unverified txns # txpos breaks ties for verified same block txns (status, conf, -height, -txpos), HistoryColumns.STATUS_TEXT: status_str, HistoryColumns.BLANK: '', HistoryColumns.DESCRIPTION: tx_item['label'], HistoryColumns.COIN_VALUE: tx_item['value'].value, HistoryColumns.RUNNING_COIN_BALANCE: tx_item['balance'].value, HistoryColumns.FIAT_VALUE: tx_item['fiat_value'].value if 'fiat_value' in tx_item else None, HistoryColumns.FIAT_ACQ_PRICE: tx_item['acquisition_price'].value if 'acquisition_price' in tx_item else None, HistoryColumns.FIAT_CAP_GAINS: tx_item['capital_gain'].value if 'capital_gain' in tx_item else None, HistoryColumns.TXID: tx_hash, } return QVariant(d[col]) if role not in (Qt.DisplayRole, Qt.EditRole): if col == HistoryColumns.STATUS_ICON and role == Qt.DecorationRole: return QVariant(read_QIcon(TX_ICONS[status])) elif col == HistoryColumns.STATUS_ICON and role == Qt.ToolTipRole: return QVariant( str(conf) + _(" confirmation" + ("s" if conf != 1 else ""))) elif col != HistoryColumns.DESCRIPTION and role == Qt.TextAlignmentRole: return QVariant(Qt.AlignRight | Qt.AlignVCenter) elif col != HistoryColumns.DESCRIPTION and role == Qt.FontRole: monospace_font = QFont(MONOSPACE_FONT) return QVariant(monospace_font) elif col == HistoryColumns.DESCRIPTION and role == Qt.DecorationRole \ and self.parent.wallet.invoices.paid.get(tx_hash): return QVariant(read_QIcon("seal")) elif col == HistoryColumns.BLANK and role == Qt.ForegroundRole: BLANK_brush = QBrush(QColor("#1c75bc")) return QVariant(BLANK_brush) elif col in (HistoryColumns.DESCRIPTION, HistoryColumns.COIN_VALUE) \ and role == Qt.ForegroundRole and tx_item['value'].value < 0: red_brush = QBrush(QColor("#BC1E1E")) return QVariant(red_brush) elif col == HistoryColumns.FIAT_VALUE and role == Qt.ForegroundRole \ and not tx_item.get('fiat_default') and tx_item.get('fiat_value') is not None: blue_brush = QBrush(QColor("#1E1EFF")) return QVariant(blue_brush) return QVariant() if col == HistoryColumns.STATUS_TEXT: return QVariant(status_str) elif col == HistoryColumns.BLANK: return QVariant('') elif col == HistoryColumns.DESCRIPTION: return QVariant(tx_item['label']) elif col == HistoryColumns.COIN_VALUE: value = tx_item['value'].value v_str = self.parent.format_amount(value, is_diff=True, whitespaces=True) return QVariant(v_str) elif col == HistoryColumns.RUNNING_COIN_BALANCE: balance = tx_item['balance'].value balance_str = self.parent.format_amount(balance, whitespaces=True) return QVariant(balance_str) elif col == HistoryColumns.FIAT_VALUE and 'fiat_value' in tx_item: value_str = self.parent.fx.format_fiat(tx_item['fiat_value'].value) return QVariant(value_str) elif col == HistoryColumns.FIAT_ACQ_PRICE and \ tx_item['value'].value < 0 and 'acquisition_price' in tx_item: # fixme: should use is_mine acq = tx_item['acquisition_price'].value return QVariant(self.parent.fx.format_fiat(acq)) elif col == HistoryColumns.FIAT_CAP_GAINS and 'capital_gain' in tx_item: cg = tx_item['capital_gain'].value return QVariant(self.parent.fx.format_fiat(cg)) elif col == HistoryColumns.TXID: return QVariant(tx_hash) return QVariant()
def row(self, index: QModelIndex): return self.table_data[index.row()]
def _index_is_good(self, index: QModelIndex): res = (index.isValid() and index.row() < self._array.shape[0] and index.column() < len(self._columns)) return res
def on_item_clicked(self, e: QModelIndex, me: QMouseEvent = None) -> None: if me.button() == Qt.LeftButton: self.left_mouse_click(e.row(), e.column())