Ejemplo n.º 1
0
 def allChildren(index: QtCore.QModelIndex):
     result = [index]
     for row, column in product(
             range(index.model().rowCount(index)),
             range(index.model().columnCount(index)),
     ):
         result.extend(TreeModel.allChildren(index.child(row, column)))
     return result
    def setEditorData(self, editor, index: QModelIndex):
        """
        Overriding inherited setEditorData class
        Args:
            editor: Current editor for the data
            index: Current index being modified

        """
        m = index.model()
        d = m.data(index, Qt.DisplayRole)
        text = index.model().data(index, Qt.DisplayRole)
        if index.column() == TreeModelParamEntry.TYPE:
            text = editor.setCurrentText(text)
        else:
            QItemDelegate.setEditorData(self, editor, index)
Ejemplo n.º 3
0
    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)
Ejemplo n.º 4
0
 def createEditor(self, parent: QWidget, option: QStyleOptionViewItem, index: QModelIndex) -> QWidget:
     if index.column() == 3:
         btn = QPushButton("X", parent)
         btn.clicked.connect(lambda x: print(index.model().removeRows(index.row(), 1, index)))
         return btn
     else:
         super().createEditor(parent, option, index)
Ejemplo n.º 5
0
 def createEditor(self, parent: PySide2.QtWidgets.QWidget,
                  option: PySide2.QtWidgets.QStyleOptionViewItem,
                  index: QModelIndex) -> PySide2.QtWidgets.QWidget:
     model = index.model()
     item, column = model.item_and_column(index)
     content = item.content
     if isinstance(content,
                   ObservedValues) and item.parents_column == 'filename':
         # TODO make it better
         if item.parent().parent().get_content().is_rv():
             editor = DataOpenDialog(
                 expected_columns=['hjd', 'rv1', 'rv1_e', 'rv2', 'rv2_e'],
                 all_columns=[
                     'hjd', 'ph', 'rv1', 'rv1_e', 'rv2', 'rv2_e',
                     'instrument'
                 ],
                 obligatory_columns=[('hjd', 'ph'), 'rv1', 'rv2'])
         else:
             editor = DataOpenDialog(
                 expected_columns=['hjd', 'mag'],
                 all_columns=['hjd', 'ph', 'mag', 'mag_e'],
                 obligatory_columns=[('hjd', 'ph'), 'mag'])
         # editor = QFileDialog(directory=os.curdir, caption='Select Data File')
         # editor.setFileMode(QFileDialog.ExistingFile)
     else:
         editor = super().createEditor(parent, option, index)
     return editor
Ejemplo n.º 6
0
    def createEditor(self, parent: QWidget, option: QStyleOptionViewItem,
                     index: QModelIndex) -> QWidget:
        editor = QLineEdit(parent)
        current_value = index.model().data(index, Qt.EditRole)
        editor.setText(current_value)

        return editor
Ejemplo n.º 7
0
    def _index_is_custom_setting(self, index: QModelIndex):
        src_index = index.model().mapToSource(index)
        item: KnechtItem = index.model().sourceModel().get_item(src_index)
        setting_type = item.data(Kg.TYPE)

        if item.userType in [Kg.output_item]:
            self.setting_delegate = OutputDirButton(self.view)
            return True

        if item.userType in [Kg.plmxml_item]:
            self.setting_delegate = InputFileButton(self.view)
            return True

        if item.userType == Kg.render_setting and setting_type in RENDER_SETTING_MAP.keys(
        ):
            self.setting_delegate = RENDER_SETTING_MAP[setting_type](self.view)
            return True
        return False
Ejemplo n.º 8
0
    def checkBox_changed(self, index: QtCore.QModelIndex, value: bool):
        model = index.model()
        row = index.row()
        if not 'url' in self.df[0].keys():
            return

        url = model.get_data_for_row(row, 'url')

        if self.currentStatus == ApiResultModelStatus.INDEX:
            self.get_pages(url, index)
Ejemplo n.º 9
0
 def createEditor(self, parent: PySide2.QtWidgets.QWidget, option: PySide2.QtWidgets.QStyleOptionViewItem,
                  index: QModelIndex) -> PySide2.QtWidgets.QWidget:
     item, column = index.model().item_and_column(index)
     vals, labels = item.values_choice(column)
     if vals:
         editor = QComboBox(parent)
         editor.insertItems(0, labels)
     else:
         editor = super().createEditor(parent, option, index)
     return editor
Ejemplo n.º 10
0
    def createEditor(self, parent: QWidget, option: QStyleOptionViewItem,
                     index: QModelIndex):
        """Return editor widget for columns of PedView

        Notes:
            Family ids & Individual ids are NOT editable (we must fit with the VCF file)
        """
        # PS: index.model refer to SampleModel

        if index.column() < 2:
            # Family ids & Individual ids are NOT editable (we must fit with the VCF file)
            return

        widget = QComboBox(parent)
        if index.column() == 2 or index.column() == 3:
            # Forge a list of available individual ids except the current one
            # Get individual_id of the current row/sample
            current_individual_id = index.model().samples_data[index.row()][1]
            # Remove current individual_id from propositions
            individual_ids = set(index.model().get_data_list(1))
            individual_ids.remove(current_individual_id)
            # father_id or mother_id columns
            widget.addItem("", "0")
            for individual_id in individual_ids:
                widget.addItem(individual_id, individual_id)

            return widget

        if index.column() == 4:
            # Sex column
            widget.addItem("Male", "1")
            widget.addItem("Female", "2")
            widget.addItem("", "0")
            return widget

        if index.column() == 5:
            # Genotype column
            widget.addItem("Unaffected", "1")
            widget.addItem("Affected", "2")
            widget.addItem("", "0")
            return widget

        return super().createEditor(parent, option, index)
Ejemplo n.º 11
0
 def createEditor(
     self, parent: QWidget, option: QStyleOptionViewItem, index: QModelIndex
 ) -> QWidget:
     model = index.model()
     value = model.data(index, Qt.DisplayRole)
     frame = self.get_frame(value)
     frame.transformation_frame.enable()
     frame.setParent(parent)
     self.frameSize = frame.sizeHint()
     return frame
Ejemplo n.º 12
0
 def _table_view_double_clicked(self, item: QtCore.QModelIndex):
     """Actions when table view is double-clicked"""
     try:
         self._custom.table_view_double_clicked(
             item=item,
             row_index=item.model().headerData(item.row(),
                                               QtCore.Qt.Vertical),
             df=self._table_model.df,
             extension=self._csv_set.extension)
     except CustomError as e:
         QtWidgets.QMessageBox.warning(self, "Erreur", str(e))
Ejemplo n.º 13
0
    def _on_tree_row_changed(self, current: QModelIndex,
                             previous: QModelIndex):
        model = current.model()

        prev_item, prev_column = model.item_and_column(previous)
        curr_item, curr_column = model.item_and_column(current)

        logger().info(f'Selection changed {prev_item} -> {curr_item}')
        self.current_tree_item = curr_item

        self.treeCurrentItemChanged.emit(curr_item)
Ejemplo n.º 14
0
 def setEditorData(self, editor: QComboBox, index: QModelIndex):
     """Update the editor."""
     items = [artist.name for artist in self._manager.context.artists]
     current = index.model().data(index, RoleTaskArtist)
     try:
         row = items.index(current)
     except ValueError:  # None is not in list
         row = -1
     editor.blockSignals(True)
     editor.setCurrentIndex(row)
     editor.blockSignals(False)
Ejemplo n.º 15
0
 def paint(
     self, painter: QPainter, option: QStyleOptionViewItem, index: QModelIndex
 ):
     model = index.model()
     value = model.data(index, Qt.DisplayRole)
     frame = self.get_frame(value)
     frame.setFixedSize(option.rect.size())
     ratio = self.parent().devicePixelRatioF()
     pixmap = QPixmap(frame.size() * ratio)
     pixmap.setDevicePixelRatio(ratio)
     frame.render(pixmap, QPoint(), QRegion())
     painter.drawPixmap(option.rect, pixmap)
     if index in self.parent().selectedIndexes():
         fill_selection(option, painter)
Ejemplo n.º 16
0
 def createEditor(self, parent: QWidget, option,
                  index: QModelIndex) -> QWidget:
     # I use an OperationEditor with this delegate, since it already comes with close/accept
     # buttons, description and nice formatting
     self.w = _IntervalWidget(parent)
     self.w.setUpEditor()
     self.w.accept.connect(self.onCommit)
     self.w.reject.connect(self.onReject)
     self.w.setWindowFlags(Qt.Dialog)
     self.w.setWindowModality(Qt.WindowModal)
     columnName = index.model().index(index.row(),
                                      index.model().nameColumn,
                                      QModelIndex())
     self.w.setWindowTitle('Date intervals: {:s}'.format(
         columnName.data(Qt.DisplayRole)))
     self.w.setDescription(
         'Define the bin edges as dates or datetimes. Intervals are right-inclusive',
         long=
         'If date or time components are not both required they can be disabled.<br>'
         'Time points must define a strictly increasing time series, since they describe '
         'contiguous ranges')
     self.w.setFocusPolicy(Qt.StrongFocus)  # Advised by docs
     return self.w
Ejemplo n.º 17
0
    def _select_first_leaf(self, idx: QModelIndex, reverse):
        assert idx is not None and idx.model() is not None

        if _is_leaf(idx):
            # Check if we can select this leaf. If we can't, continue to the next item.
            if not _is_item_selectable(idx):
                self._select_next_item(idx, reverse)
                return

            self.final_item_callback(idx)
            return

        def _select_first_leaf_later():
            self._select_first_leaf(idx, reverse)

        # If the node is not expanded, we need to expand it and wait for the children to load.
        if not self.is_expanded_callback(idx):
            self.expand_callback(idx)
            self._enqueue_operation_and_pump_later(_select_first_leaf_later)
            return

        # If the node is not completely loaded, we need to fetch more items and revisit this node.
        if idx.model().canFetchMore(idx):
            idx.model().fetchMore(idx)
            self._enqueue_operation_and_pump_later(_select_first_leaf_later)
            return

        first_child = _find_first_child(idx, reverse)
        if first_child is None:
            if idx.model().hasChildren(idx):
                self._enqueue_operation_and_pump_later(
                    _select_first_leaf_later)
                return
            self._select_next_item(idx, reverse)
        else:
            self._select_first_leaf(first_child, reverse)
Ejemplo n.º 18
0
 def createEditor(
     self, parent: QWidget, option: QStyleOptionViewItem, index: QModelIndex
 ) -> QWidget:
     if index in self._dict_frames:
         frame = self._dict_frames[index]
     else:
         model = index.model()
         value = model.data(index, Qt.DisplayRole)
         frame = self.get_frame(value)
     if hasattr(frame, TRANSFORMATION_FRAME):
         frame.transformation_frame.enable()
     if hasattr(frame, MODULE_FRAME):
         frame.module_frame.setEnabled(True)
     frame.setParent(parent)
     self.frameSize = frame.sizeHint()
     return frame
Ejemplo n.º 19
0
def _find_first_child(idx: QModelIndex, reverse: bool):
    model: QFileSystemModel = idx.model()
    files = list(_iter_children(idx))
    if len(files) == 0:
        return None

    # We need the children to be in the same order as in QFileSystemModel. Otherwise we will sometimes select a random
    # item in the directory.

    children = _qt_stort_files(files, reverse=reverse)

    for row in children:
        if model.isDir(row):
            return row
        if _is_item_selectable(row):
            return row
    return None
Ejemplo n.º 20
0
    def _set_data(index: QModelIndex, data, parent_user_data):
        model = index.model()
        model.setData(index, data)

        # Flag the parent with UserData that some child has been edited(or not on Undo)
        if index.parent().isValid():
            result = model.setData(index.parent().siblingAtColumn(0),
                                   parent_user_data, Qt.UserRole)

            if result and parent_user_data:
                # Style italic, children contain item edits
                model.setData(index.parent().siblingAtColumn(0),
                              FontRsc.italic, Qt.FontRole)
            else:
                # Style regular, children have not been edited
                model.setData(index.parent().siblingAtColumn(0),
                              FontRsc.regular, Qt.FontRole)
    def createEditor(self, parent: QWidget, option: QStyleOptionViewItem,
                     index: QModelIndex) -> QWidget:
        """
        Overriding inherited createdEditor class
        Args:
            parent: Parent widget
            option: Style options for the related view
            index: Specific index being edited

        Returns:

        """
        if index.column() == TreeModelParamEntry.TYPE:
            node = index.model().nodeFromIndex(index)
            combo = node.get_type_combobox(parent)  #dicts vs values
            #combo.setEditable(True)
            return combo
        else:
            return QItemDelegate.createEditor(self, parent, option, index)
    def createEditor(self, parent: QWidget, option: QStyleOptionViewItem,
                     index: QModelIndex) -> QWidget:
        """
        Overriding inherited createdEditor class.
        Note that the index contains information about the model being used.
        The editor's parent widget is specified by parent, and the item options by option.

        Args:
            parent: Parent widget
            option: Style options for the related view
            index: Specific index being edited

        Returns:
            Returns the editor to be used for editing the data item with the given index.
        """
        if index.column() == TreeModelParamEntry.TYPE:
            node = index.model().nodeFromIndex(index)
            combo = node.get_type_combobox(parent)  #dicts vs values
            return combo

        return QItemDelegate.createEditor(self, parent, option, index)
Ejemplo n.º 23
0
    def __init__(self, parent_cmd: TreeOrderCommandChain, editor,
                 index: QModelIndex, new_order: int):
        """ Re-order items by re-writing the order column.

        :param parent_cmd:
        :param modules.itemview.editor.KnechtEditor editor:
        :param index:
        :param new_order:
        """
        super(TreeOrderCommand, self).__init__(parent_cmd)

        self.debug = TreeUndoCommandChainWorker.debug

        self.editor = editor
        self.new_order = new_order
        self.model: KnechtModel = index.model()
        self.position = index.row()
        self.parent_idx = index.parent()
        self.parent_position = index.parent().row()

        # Make sure index is in Order column
        self.index = self.model.sibling(index.row(), Kg.ORDER, index)

        self.current_order = int(self.index.data())
Ejemplo n.º 24
0
 def setEditorData(self, editor: PySide2.QtWidgets.QWidget,
                   index: QModelIndex) -> None:
     value = index.model().data(index, Qt.EditRole)
     editor.setValue(int(value))
Ejemplo n.º 25
0
 def sizeHint(self, option: QStyleOptionViewItem, index: QModelIndex) -> QSize:
     model = index.model()
     value = model.data(index, Qt.DisplayRole)
     frame = self.get_frame(value)
     return frame.sizeHint()
 def setEditorData(self, editor: QWidget, index: QModelIndex):
     model = index.model()
     text = model.data(index, Qt.EditRole)
     editor.setValue(float(text))
 def setEditorData(self, editor: QWidget, index: QModelIndex):
     value = index.model().data(index, Qt.EditRole)
     editor.setText(value)
Ejemplo n.º 28
0
 def proxy_to_source(proxy: QModelIndex) -> QModelIndex:
     """Step from the QSortFilterProxyModel to the underlying PandasModel."""
     model = proxy.model()
     if not hasattr(model, "mapToSource"):
         return proxy  # Proxy is actually the PandasModel
     return model.mapToSource(proxy)
Ejemplo n.º 29
0
 def field_name(self, index: QModelIndex):
     return index.model().headerData(index.column(), Qt.Horizontal)
 def setEditorData(self, editor: QWidget, index: QModelIndex):
     value = index.model().data(index,Qt.EditRole)
     if value != None:
         editor.setValue(value)
     else:
         editor.setValue(0)