예제 #1
0
 def edit_single_parameter(self, index: QModelIndex) -> None:
     """Take the index and update the underlying brightway Parameter."""
     param = self.get_parameter(index)
     field = self._dataframe.columns[index.column()]
     signals.parameter_modified.emit(param, field, index.data())
예제 #2
0
    def setData(self,
                index: QModelIndex,
                value,
                role: Qt.ItemDataRole = Qt.EditRole) -> bool:
        """Set the LeafNode value and corresponding data entry to value.
        Returns true if successful; otherwise returns false. The dataChanged()
        signal should be emitted if the data was successfully set.

        Args:
            index (QModelIndex): The index
            value: The value
            role (Qt.ItemDataRole): The role of the data..  Defaults to Qt.EditRole.

        Returns:
            bool: True if successful, False otherwise
        """

        if not index.isValid():
            return False

        elif role == QtCore.Qt.EditRole:

            if index.column() == 1:
                node = self.nodeFromIndex(index)

                if isinstance(node, LeafNode):
                    value = str(value)  # new value
                    old_value = node.value  # option value

                    if old_value == value:
                        return False

                    # Set the value of an option when the new value is different
                    else:
                        dic = self.data_dict  # option dict
                        lbl = node.label  # option key

                        self.logger.info(
                            f'Setting {self.optionstype} option {lbl:>10s}: old value={old_value}; new value={value};'
                        )

                        ##### Parse value if not str ##############################
                        # Somewhat legacy code for extended handling of non string options
                        # These days we tend to have all options be strings, so not so releavnt, but keep here for now
                        # to allow extended use in te future
                        if not isinstance(old_value, str):
                            processed_value, used_ast = parse_param_from_str(
                                value)
                            self.logger.info(f'  Used paring:  Old value type={type(old_value)}; '\
                                             f'New value type={type(processed_value)};'\
                                             f'  New value={processed_value};'\
                                             f'; Used ast={used_ast}')
                            value = processed_value
                        #################################################

                        if node.path:  # if nested option
                            for x in node.path[:-1]:
                                dic = dic[x]
                            dic[node.path[-1]] = value
                        else:  # if top-level option
                            dic[lbl] = value
                        if self.optionstype == 'component':
                            self.component.rebuild()
                            self.gui.refresh()
                        return True
        return False
 def get_element(self, index: QtCore.QModelIndex):
     if index.isValid():
         element = self._data[index.row()][index.column()]
         if element:
             return element
     return None
예제 #4
0
def onEdit( index:QModelIndex ):
    print( "onEdit, %d/%d" % (index.row(), index.column() ) )
예제 #5
0
 def data(self, index: QModelIndex, role: int = ...) -> Any:
     if index.isValid():
         if role == Qt.DisplayRole:
             return str(self.__frame.getRawFrame().iloc[index.row(),
                                                        index.column()])
     return None
예제 #6
0
 def flags(self, index: QtCore.QModelIndex) -> QtCore.Qt.ItemFlags:
     if index.column() == 0 and index.row() > 0:
         return QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable  # type: ignore
     else:
         return QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable  # type: ignore
예제 #7
0
 def flags(self, index: QModelIndex) -> Qt.ItemFlags:
     f = super().flags(index)
     if index.column() in self._optionsPos.keys() and index.row(
     ) in self.checked:
         f |= Qt.ItemIsEditable
     return f
예제 #8
0
 def data(self, index: QModelIndex, role: int):
     return self._value(index.row(), index.column())
예제 #9
0
 def data(self, index: QModelIndex, role: int) -> Any:
     if role == Qt.DisplayRole:
         return self.source[index.row()][index.column()]
예제 #10
0
def doEdit(idx: QModelIndex):
    print("Edit %d/%d" % (idx.row(), idx.column()))
예제 #11
0
 def data(self, index: QtCore.QModelIndex, role: int=...):
     if role == QtCore.Qt.DisplayRole:
         if index.column() == 0:
             return self.offers[index.row()].rating
         return self.offers[index.row()].options[index.column() - 1].name
예제 #12
0
 def _onLeftClick(self, item: QModelIndex):
     tm: AnlageVTableModel = self.model()
     self.cell_clicked.emit(tm.getMasterName(), item.row(), item.column())
예제 #13
0
 def flags(self, index: QtC.QModelIndex) -> QtC.Qt.ItemFlags:
     if self.getDirFrame(index) is not None:
         return QtC.Qt.ItemIsSelectable | QtC.Qt.ItemIsEditable | QtC.Qt.ItemIsEnabled | QtC.Qt.ItemNeverHasChildren
     if index.column() == self.summaryColumn():
         return QtC.Qt.ItemNeverHasChildren | QtC.Qt.ItemIsEnabled
     return QtC.Qt.ItemNeverHasChildren
예제 #14
0
 def getDirFrame(self, index: QtC.QModelIndex) -> Optional[Tuple[int, int]]:
     framesInDirection = self.frames(index.row())
     if index.column() >= len(framesInDirection):
         return None
     return (index.row(), index.column())
예제 #15
0
 def setModelData(self, editor: QWidget, model: QtCore.QAbstractItemModel,
                  index: QtCore.QModelIndex) -> None:
     if index.isValid() and index.column() == 0:
         editor.interpretText()
         model.setData(index, editor.value(), Qt.EditRole)
예제 #16
0
 def flags(self, index: QModelIndex) -> Qt.ItemFlags:
     flags = super().flags(index)
     if index.column() == 1:
         flags |= Qt.ItemIsEditable
     return flags
예제 #17
0
def _next_sibling(idx: QModelIndex, reverse: bool):
    return idx.sibling(idx.row() + (-1 if reverse else 1), idx.column())
예제 #18
0
    def setData(self,
                index: QtCore.QModelIndex,
                value,
                role=QtCore.Qt.EditRole) -> bool:
        """Sets the role data for the item at index to value. The dataChanged()
        signal should be emitted if the data was successfully set.

        Arguments:
            index (QtCore.QModelIndex): The index
            value (str): The value
            role (QtCore.Qt.EditRole): The edit role

        Returns:
            bool: Returns true if successful; otherwise returns false.
        """

        # TODO: handle nested dictionaries
        # See v0.1: get_nested_dict_item, pop_nested_dict_item
        # TODO: ability to add dictionary such as to add pins
        if not index.isValid():
            return False

        elif role == QtCore.Qt.EditRole:
            if index.column() == 1:
                self._value = value  # QString
                value = str(value)

                data = self.component.options  # type: dict
                key, old_val = list(data.items())[index.row()]

                # When we do nothing
                if isinstance(old_val, dict):
                    self.logger.error(
                        'You selected a dicitonary this'
                        'cannot be edited directly edit its items.')
                    return False

                if old_val == value:
                    return False

                # When we do something to change the value

                # try:
                # TODO: should retry and if error then reset the value
                if 1:
                    self.logger.info(
                        f'Component options: Old value={old_val}; New value={value};'
                    )
                    if isinstance(old_val, str):
                        data[key] = str(value)
                    else:
                        processed_value, used_ast = parse_param_from_str(value)
                        self.logger.info(
                            f'  Used paring:  Old value type={type(old_val)}; '
                            f'New value type={type(processed_value)};  New value={processed_value};'
                            f'; Used ast={used_ast}')
                        data[key] = processed_value

                    self.component.rebuild()
                    self.gui.refresh()

                # except and finally restore the value
                return True

        # elif role == Qt.CheckStateRole:

        return False
 def setData(self, index: QModelIndex, value: typing.Any, role=...) -> bool:
     if index.isValid() and role == Qt.EditRole and value:
         self.array[index.row()][index.column()] = value
         self.dataChanged.emit(index, index)
         return True
     return False
예제 #20
0
파일: main.py 프로젝트: yenru0/antanswer
 def flags(self, index: QModelIndex) -> Qt.ItemFlags:
     if index.column() == 2:
         return Qt.ItemIsEnabled | Qt.ItemIsSelectable | Qt.ItemIsUserCheckable
     else:
         return Qt.ItemIsEnabled | Qt.ItemIsSelectable
 def data(self, index: QModelIndex, role: int = ...) -> str:
     if role == Qt.DisplayRole or role == Qt.EditRole:
         value = self.array[index.row()]
         if not np.isscalar(value):
             value = value[index.column()]
         return str(value)
예제 #22
0
파일: main.py 프로젝트: yenru0/antanswer
 def paint(self, painter: QPainter, option: QStyleOptionViewItem, index: QModelIndex):
     if index.column() == 2:
         v = index.data(Qt.CheckStateRole)
         self.drawCheck(painter, option, option.rect, Qt.Checked if v else Qt.Unchecked)
     else:
         super().paint(painter, option, index)
예제 #23
0
 def data(self, index: QtCore.QModelIndex, role: int=...):
     if role == QtCore.Qt.DisplayRole and self.issue_selected != -1:
         if index.column() == 0:
             return self.issues[self.issue_selected].options[index.row()].name
         elif index.column() == 1:
             return self.issues[self.issue_selected].options[index.row()].rating
예제 #24
0
    def paint(self, painter: QPainter, option: QStyleOptionViewItem,
              index: QModelIndex):
        """
        Displays dirty files in red with corresponding rebuild buttons
        if in developer mode (is_dev_mode). Otherwise, renders normally


        Args:
            painter (QPainter): Current painter
            option (QStyleOptionViewItem): Current option
            index (QModelIndex): Current index of related model



        """
        if self.is_dev_mode:
            source_model = self.get_source_model(index.model(),
                                                 self.source_model_type)

            model = index.model()

            # get data of filename
            filename = str(
                model.data(
                    model.sibling(index.row(), source_model.FILENAME, index)))

            if source_model.is_file_dirty(filename):
                if index.column() == source_model.FILENAME:

                    text = filename
                    palette = option.palette
                    document = QTextDocument()
                    document.setDefaultFont(option.font)
                    document.setHtml(f"<font color={'red'}>{text}</font>")
                    background_color = palette.base().color()
                    painter.save()
                    painter.fillRect(option.rect, background_color)
                    painter.translate(option.rect.x(), option.rect.y())
                    document.drawContents(painter)
                    painter.restore()

                elif index.column() == source_model.REBUILD:
                    if '.py' in filename:
                        text = "rebuild"
                        palette = option.palette
                        document = QTextDocument()
                        # needed to add Right Alignment:  qt bug :
                        # https://bugreports.qt.io/browse/QTBUG-22851
                        document.setTextWidth(option.rect.width())
                        text_options = document.defaultTextOption()
                        text_options.setTextDirection(Qt.RightToLeft)
                        document.setDefaultTextOption(
                            text_options)  # get right alignment
                        document.setDefaultFont(option.font)
                        document.setHtml(
                            f'<font color={"red"}> <b> {text}</b> </font>')
                        background_color = palette.base().color()
                        painter.save()
                        painter.fillRect(option.rect, background_color)
                        painter.translate(option.rect.x(), option.rect.y())
                        document.drawContents(painter)
                        painter.restore()

            else:
                QItemDelegate.paint(self, painter, option, index)

        else:
            QItemDelegate.paint(self, painter, option, index)
예제 #25
0
 def field_name(self, index: QModelIndex):
     return index.model().headerData(index.column(), Qt.Horizontal)
예제 #26
0
 def flags(self, index: QModelIndex) -> Qt.ItemFlags:
     if index.isValid():
         if index.column() == 0:
             return Qt.ItemIsEditable | Qt.ItemIsSelectable | Qt.ItemIsEnabled
         return Qt.ItemIsEnabled
     return Qt.NoItemFlags
예제 #27
0
    def setData(
            self,  # pylint: disable=too-many-return-statements
            index: QModelIndex,
            value: Any,
            role: Qt.ItemDataRole = Qt.EditRole) -> bool:
        """Set the LeafNode value and corresponding data entry to value.
        Returns true if successful; otherwise returns false.
        The dataChanged() signal should be emitted if the data was successfully set.

        Args:
            index (QModelIndex): The index
            value (Any): The value
            role (Qt.ItemDataRole): The role of the data (Default: Qt.EditRole)

        Returns:
            bool: True if successful, False otherwise
        """
        try:

            if not index.isValid():
                return False

            if role == QtCore.Qt.EditRole:

                if index.column(
                ) == self.VALUE:  # only want to edit col1 if it's a leafnode

                    node = self.nodeFromIndex(index)

                    if isinstance(node, LeafNode):

                        value = str(value)  # new value
                        old_value = node.value  # option value

                        if old_value == value:
                            return False

                        # Set the value of an option when the new value is different
                        node.value = value  # # pylint: disable=attribute-defined-outside-init
                        return True  # why doesn't this require a self.init_load()?

                elif index.column(
                ) == self.NAME:  # either editing BranchNode name or LeafNode name
                    node = self.nodeFromIndex(index)
                    if node.parent is None:
                        raise Exception(
                            "Trying to edit node without a parent. "
                            "The root node should be uneditable.")

                    old_value = node.name
                    if old_value == value:
                        return False

                    node.update_name(value)

                    cop = self.get_path_of_expanded_items()

                    self.reload()
                    self.expand_items_in_paths(cop)

                    # update node
                    # at each parent:
                    # data.emit changed from 0,0 to len(children), lenCol
                    return True
                elif index.column() == self.TYPE:
                    # this is a type
                    node = self.nodeFromIndex(
                        self.index(index.row(), 0, index.parent()))
                    node.type = value

                    cop = self.get_path_of_expanded_items()

                    self.reload()
                    self.expand_items_in_paths(cop)
                    return True

            return False
        except Exception as e:  # pylint: disable=broad-except
            self._design.logger.error(f"Unable to parse tree information: {e}")
            return False
예제 #28
0
 def setEditorData(self, editor: QWidget,
                   index: QtCore.QModelIndex) -> None:
     if index.isValid() and index.column() == 0:
         editor.setValue(index.model().data(index, Qt.EditRole))
예제 #29
0
 def flags(self, index: QModelIndex) -> Qt.ItemFlags:
     base = Qt.ItemIsEnabled | Qt.ItemIsSelectable | super().flags(index)
     if index.column() == 0:
         base |= Qt.ItemIsEditable
     return base
예제 #30
0
    def data(self,
             index: QModelIndex,
             role: Qt.ItemDataRole = Qt.DisplayRole) -> Any:
        if not index.isValid():
            return None
        col = self.getColumnKey(index.column())
        if not col:
            return None

        if role == Qt.FontRole:
            if col in (
                    'datatype',
                    'size',
            ):
                return QFontDatabase.systemFont(QFontDatabase.FixedFont)
            return None

        if role == Qt.CheckStateRole:
            if col in ('enabled', ):
                mod = self.modmodel[index.row()]
                val = mod[col]
                return Qt.Checked if val else Qt.Unchecked
            return None

        if role == Qt.BackgroundRole:
            mod = self.modmodel[index.row()]
            if not mod.enabled:
                return QColor(240, 240, 240)
            if col in ('priority', ) and mod.datatype not in (
                    'mod',
                    'udf',
            ):
                return QColor(240, 240, 240)
            if mod.installdate > self._lastUpdate:
                return QColor(242, 255, 242)
            if mod.installdate > self._lastInitialization:
                return QColor(242, 246, 255)
            if not mod.installed:
                return QColor(250, 240, 240)
            return None

        if role == Qt.ForegroundRole:
            mod = self.modmodel[index.row()]
            if not mod.enabled:
                return QColor(60, 60, 60)
            return None

        if role == Qt.DecorationRole:
            if col in ('datatype', ):
                mod = self.modmodel[index.row()]
                val = mod[col]
                return self._icons[val] if val in self._icons else self._icons[
                    'udf']
            return None

        if role == Qt.ToolTipRole:
            mod = self.modmodel[index.row()]
            if col in ('datatype', ):
                val = mod[col]
                return self._datatypes[
                    val] if val in self._datatypes else self._datatypes['udf']
            if col in ('enabled', ):
                val = mod[col]
                return 'Enabled' if val else 'Disabled'
            return str(mod[col])

        if role == Qt.TextAlignmentRole:
            if col in ('size', ):
                # Right|VCenter
                return 0x0082
            if col in (
                    'priority',
                    'installdate',
                    'binFiles',
                    'menuFiles',
                    'settings',
                    'inputs',
                    'contentFiles',
                    'scriptFiles',
            ):
                # HCenter|VCenter
                return 0x0084
            # Left|VCenter
            return 0x0081

        if role == Qt.EditRole:
            if col in (
                    'package',
                    'filename',
                    'category',
                    'priority',
            ):
                mod = self.modmodel[index.row()]
                return str(mod[col])
            return None

        # role used for sorting
        if role == Qt.UserRole:
            mod = self.modmodel[index.row()]
            if col in ('priority', ):
                return f'{int(mod[col]): >20} {mod["filename"]}'
            if col in ('size', ):
                return int(mod[col])
            if col in ('binFiles', 'menuFiles', 'contentFiles', \
                       'scriptFiles', 'settings', 'inputs',):
                return len(mod[col])
            return str(mod[col])

        if role == Qt.DisplayRole:
            if col in ('enabled', ):
                return None
            mod = self.modmodel[index.row()]
            if col in ('datatype', ):
                return str(mod[col]).upper()
            if col in ('priority', ):
                val = mod[col]
                if val <= 0:
                    return 'none'
                return val
            if col in ('installdate', ):
                return mod[col].astimezone(
                    tz=None).strftime('%Y-%m-%d %H:%M:%S')
            if col in ('size', ):
                val = mod[col]
                frm = 'b'
                val /= 1024
                frm = 'K'
                if val // 1024:
                    val /= 1024
                    frm = 'M'
                return '%.1f %s' % (val, frm)
            if col in (
                    'inputs',
                    'settings',
            ):
                val = 0
                for s in mod[col]:
                    for n in s.config.sections():
                        val += len(s.config.items(n))
                return val if val else None

            if col in (
                    'binFiles',
                    'menuFiles',
                    'contentFiles',
                    'scriptFiles',
            ):
                val = len(mod[col])
                if val < 1:
                    return ''
                return val
            return str(mod[col])

        return None