def __init__(self, *args, **kwargs): QAbstractItemModel.__init__(self) self.ds = DataSource() self.cats = self.ds.get_categories() self.categories = [] for cat in self.cats: self.categories.append(CategoryItem(self, cat))
def setModelData(self, editor: QWidget, model: QAbstractItemModel, index: QModelIndex): """Set the data for the item at the given index in the model to the contents of the given editor. """ if isinstance(editor, QComboBox): model.setData(index, editor.currentData()) if index.column() == 2 or index.column() == 3: row = index.row() model = index.model() # Detect parthenogenesis: same mother and father father_id = model.samples_data[row][2] # Only for not unknown parents if father_id != "0" and father_id == model.samples_data[row][3]: self.erroneous_samples.add(row) elif row in self.erroneous_samples: # Reset interface self.parthenogenesis_detected.emit("") self.erroneous_samples.remove(row) for row in self.erroneous_samples: self.parthenogenesis_detected.emit( self.tr("<b>Same father and mother for sample '{}'</b>"). format(model.samples_data[row][1])) return # Basic text not editable return super().setModelData(editor, model, index)
def setModelData(self, editor: '_IntervalWidget', model: QAbstractItemModel, index: QModelIndex) -> None: datetimes: List[QDateTime] datetimes, byDate, byTime = editor.getOptions() # Do some validation errors = list() if len(datetimes) < 2: errors.append(('e1', 'Error: at least one range must be defined')) if any([a >= b for a, b in zip(datetimes, datetimes[1:])]): errors.append( ('e2', 'Error: datetime points must be strictly increasing')) if errors: editor.handleErrors(errors) # Avoid setting options and leave editor open return options = ([ pd.Timestamp(date.toPython(), tz='UTC') for date in datetimes ], byDate, byTime) model.setData(index, options, Qt.EditRole) # Resize rows. This assumes that the TableView is the delegate parent f = QFontMetrics(QFont()) rowHeight = f.height() * len(options[0]) table: QTableView = self.parent() table.setRowHeight(index.row(), rowHeight) # Close editor. Works because it's the delegate that tells the view to close it with this signal self.closeEditor.emit(self.w, QStyledItemDelegate.NoHint)
def setModelData(self, editor: QLineEdit, model: QAbstractItemModel, index: QModelIndex) -> None: stringList: str = editor.text() stringEdges: List[str] = splitString(stringList, sep=' ') # If number are valid set them, otherwise leave them unchanged if all(map(isFloat, stringEdges)): edges: List[float] = [float(x) for x in stringEdges] model.setData(index, edges, Qt.EditRole)
def setModelData(self, editor: QtWidgets.QComboBox, model: QtCore.QAbstractItemModel, index: QtCore.QModelIndex): """ Take the editor, read the given value and set it in the model. """ value = editor.currentText() model.setData(index, value, QtCore.Qt.EditRole)
def setModelData(self, editor: QtWidgets.QWidget, model: QtCore.QAbstractItemModel, index: QtCore.QModelIndex): """ Take the editor, read the given value and set it in the model """ dialog = editor.findChild(OrderedListInputDialog) value = dialog.items_selected() model.setData(index, value, QtCore.Qt.EditRole)
def setModelData(self, editor: QtWidgets.QComboBox, model: QtCore.QAbstractItemModel, index: QtCore.QModelIndex): """ Read the current text and look up the actual ID of that uncertainty type. """ uc_id = self.choices.get(editor.currentText(), 0) model.setData(index, uc_id, QtCore.Qt.EditRole)
def setModelData(self, editor: QComboBox, model: QAbstractItemModel, index: QModelIndex) -> None: selectedIndex: int = editor.currentIndex() mi = QPersistentModelIndex() if selectedIndex is not None and selectedIndex >= 0: mi = QPersistentModelIndex( self.__timeLabelModel.index(selectedIndex)) model.setData(index, mi, Qt.EditRole)
def _set_time( model: QAbstractItemModel, current_index: Union[File, FileWriter], current_time: str, time_str: str, ): model.setData(model.index(current_index.row, 1), time_str) current_index.last_time = current_time
def _assert_model_rows_equal( model: QtCore.QAbstractItemModel, expected: List[Any], role: int = QtCore.Qt.DisplayRole, ): num_rows = model.rowCount() actual = [model.data(model.index(row, 0), role) for row in range(num_rows)] assert actual == expected
def __init__(self, in_nodes): QAbstractItemModel.__init__(self) self._root = Node(None) self._in_nodes = in_nodes for node in in_nodes: self._root.addChild(node) self.headers = [self.tr('Project Content')]
def editorEvent(self, event: QEvent, model: QAbstractItemModel, option: QStyleOptionViewItem, index: QModelIndex) -> bool: if index.column() == 2: if event.type() is QEvent.MouseButtonPress: v = bool(model.data(index, Qt.CheckStateRole)) model.setData(index, not v, Qt.CheckStateRole) event.accept() else: pass return super().editorEvent(event, model, option, index)
def setModelData(self, editor: QtWidgets.QLineEdit, model: QtCore.QAbstractItemModel, index: QtCore.QModelIndex): """ Take the editor, read the given value and set it in the model """ try: value = float(editor.text()) model.setData(index, value, QtCore.Qt.EditRole) except ValueError: pass
def setModelData(self, editor: QLineEdit, model: QAbstractItemModel, index: QModelIndex) -> None: rangeText: str = editor.text().strip() floatList: List[str] = splitString(rangeText, ' ')[:2] if not all(map(isFloat, floatList)) or len(floatList) != 2: d = None else: d = (float(floatList[0]), float(floatList[1])) model.setData(index, d, Qt.EditRole)
def __init__(self, propData: object): """ Constructs a model for the Property Editor. :param propData: The data from the properties. :type propData: object :return: The constructed model. :rtype: QObject """ QAbstractItemModel.__init__(self) self._propData = propData
def __init__(self, parent=None): """ """ QAbstractItemModel.__init__(self, parent) self._header_labels = ['parameter', 'value'] self._root = PhilItem() # PHIL self._scope = None self._extract = None
def _assert_horizontal_header_equal( model: QtCore.QAbstractItemModel, expected: List[Any], role: int = QtCore.Qt.DisplayRole, ): num_cols = model.columnCount() actual = [ model.headerData(column, QtCore.Qt.Horizontal, role) for column in range(num_cols) ] assert actual == expected
def setModelData(self, editor: QtWidgets.QWidget, model: QtCore.QAbstractItemModel, index: QtCore.QModelIndex): """ Take the editor, read the given value and set it in the model. If the new formula is the same as the existing one, do not call setData """ dialog = editor.findChild(FormulaDialog) if dialog.result() == QtWidgets.QDialog.Rejected: # Cancel was clicked, do not store anything. return model.setData(index, dialog.formula, QtCore.Qt.EditRole)
def _assert_model_data_equal( model: QtCore.QAbstractItemModel, expected: List[List[Any]], role: int = QtCore.Qt.DisplayRole, ): num_rows = model.rowCount() num_cols = model.columnCount() actual = [[ model.data(model.index(row, column), role) for column in range(num_cols) ] for row in range(num_rows)] assert actual == expected
def __init__(self): QAbstractItemModel.__init__(self) self.vfs_view: Optional[VfsView] = None self.gdc_body_uids = set() self.root_node = None self.n_rows = 0 self.n_cols = 0 self.header_labels = \ ("Path", "Index", "Type", "Sub_Type", "Hash", "EXT_Hash", "Size_U", "Size_C", "G, H, S", "Notes") self.vfs_changed_signal.connect(self.update_model)
def index(self, in_row, in_column, in_parent=None): if not in_parent or not in_parent.isValid(): parent = self._root else: parent = in_parent.internalPointer() if not QAbstractItemModel.hasIndex(self, in_row, in_column, in_parent): return QModelIndex() child = parent.child(in_row) if child: return QAbstractItemModel.createIndex(self, in_row, in_column, child) else: return QModelIndex()
def __init__(self, project: 'Project', view: QTreeView) -> 'ProjectExplorerModel': """ Constructs a ProjectExplorerModel exception :param project: A Facile project object. :type project: Project """ QAbstractItemModel.__init__(self) self._project = project self._view = view # Data structures that let us efficiently store references to internal data without hogging exorbitant amounts # of memory. self._registryCounter = 0 self._forwardRegistry = {} self._backwardRegistry = {}
def get_source_model(self, model: QAbstractItemModel, source_type: type): # pylint: disable=R0201, no-self-use """ The Delegate may belong to a view using a ProxyModel. However, the source model for that Proxy Model(s) should be a QFileSystemLibraryModel and is returned by this function Arguments: model(QAbstractItemModel): Current model source_type(type): Expected source model type Returns: QFileSystemLibraryModel: Source model Raises: QLibraryGUIException: If unable to find the source model for the given model """ while True: # https://stackoverflow.com/questions/50478661/python-isinstance-not-working-as-id-expect if model.__class__.__name__ == source_type.__name__: return model if isinstance(model, QAbstractProxyModel): model = model.sourceModel() else: raise QLibraryGUIException( f"Unable to find source model: " f"\n Expected Type is:" f"\n{source_type}" f"\n First non-proxy model type found is" f"\n{type(model)} for" f"\n{model}")
def flags(self, index): flags = QAbstractItemModel.flags(self, index) if index.column() == 1: flags = Qt.ItemIsEditable | flags return flags
def setModelData(self, editor, model: QAbstractItemModel, index): """ Overriding inherited setModelData class Args: editor: Current editor for the data model: Current model whose data is being set index: Current index being modified """ if index.column() == TreeModelParamEntry.TYPE: model.setData(index, editor.getTypeName()) # get type # get corresponding dict entry # update type (OrderedDict, str, etc.) as necessary # get value else: QItemDelegate.setModelData(self, editor, model, index)
def setModel(self, model: QtCore.QAbstractItemModel): """Overriding setModel to hook up clean/dirty file signals to model before setting Model Args: model (QtCore.QAbstractItemModel): Model to be set Raises: Exception: QLibraryGUIException if model is not LibraryFileProxyModel """ if not isinstance(model, LibraryFileProxyModel): raise QLibraryGUIException( f"Invalid model. Expected type {LibraryFileProxyModel} but got type {type(model)}" ) source_model = model.sourceModel() self.qlibrary_rebuild_signal.connect(source_model.clean_file) source_model.file_dirtied_signal.connect(self.update) source_model.file_dirtied_signal.connect(self.raise_dirty_file) source_model.file_cleaned_signal.connect(self.update) super().setModel(model)
def __init__(self): """Class constructor. Calls `_getRootNodes` to build the tree structure """ QAbstractItemModel.__init__(self) self.rootNodes = self._getRootNodes()
def __init__(self, parent, bv): QAbstractItemModel.__init__(self, parent) self.bv = bv self.columns = ["Enabled", "Location", "Remote Address"] self.update_rows(None)
def context_append_row(model: QAbstractItemModel, num_row: int): """Helper, context manager that add N rows at the end of a model.""" row_count = model.rowCount() model.beginInsertRows(QModelIndex(), row_count, row_count + num_row - 1) yield model.endInsertRows()
def __init__(self, parent): QAbstractItemModel.__init__(self, parent) self.columns = ["TID", "Location"] self.rows = [] self.update_rows(None)