コード例 #1
0
    def frameDataChanged(
        self,
        topLeft: QtC.QModelIndex,
        bottomRight: QtC.QModelIndex,
        roles: List[int] = list()) -> None:
        # Some data has changed - so we need to regenerate the
        # animations in the summary. First, we calculate which
        # rows are different now

        if (topLeft.column() < self.summaryColumn()):
            # +1, because these are inclusive and range is exclusive
            rowsChanged = range(topLeft.row(), bottomRight.row() + 1)

            self.recalculateSummary(rowsChanged)
コード例 #2
0
    def __on_double_clicked(self, model_index: QModelIndex):
        """
        Displays the edition dialog popup for the topic.

        The doubleClicked event is triggered after the "simple" clicked event. So this method will be called after
        the selection changed one.
        """
        if model_index.column() == 1:
            dlg = VTopicSelectionDialog(self, self.topics, self.datamodel.index(model_index.row(), 1).data(),
                                        self.datamodel.index(model_index.row(), 0).data())
            if dlg.exec_():
                new_topic = dlg.new_topic()
                if new_topic:
                    self.sig_topic_changed.emit(new_topic)
コード例 #3
0
 def data(self, index: QModelIndex, role: int = None):
     if not index.isValid():
         return None
     if role == Qt.DisplayRole:
         return self.getValue(index.row(), index.column())
     elif role == Qt.TextAlignmentRole:
         return self.getAlignment(index.row(), index.column())
     elif role == Qt.ForegroundRole:
         return self.getForeground(index.row(), index.column())
     elif role == Qt.FontRole:
         return self.getFont(index.row(), index.column())
     elif role == Qt.BackgroundRole:
         return self.getBackground(index.row(), index.column())
     return None
コード例 #4
0
 def setData(self,
             index: QModelIndex,
             value: typing.Any,
             role: int = ...) -> bool:
     if role == Qt.EditRole and index.column() == 0:
         item_id = self.get_item_id(index.row())
         if item_id in self.selected.keys():
             self.selected[item_id].count = value
         elif value > 0:
             item = Merchandise.from_sql_record(self.sourceModel().record(
                 index.row()))
             item.count = value
             self.selected[item.id] = item
         return True
     return False
コード例 #5
0
 def data(self, index: QtCore.QModelIndex, role: int = ...) -> typing.Any:
     if role == QtCore.Qt.DisplayRole:
         music = self._player.getFrontPlaylist().orElseThrow(
             AssertionError).musics[index.row()]
         return ("", music.artist, music.title)[index.column()]
     elif role == QtCore.Qt.DecorationRole:
         currentPlaylistIndex = self._player.getCurrentPlaylistIndex()
         frontPlaylistIndex = self._player.getFrontPlaylistIndex()
         currentMusicIndex = self._player.getCurrentMusicIndex()
         if index.column() == 0 and index.row(
         ) == currentMusicIndex and currentPlaylistIndex == frontPlaylistIndex:
             playerState = self._player.getState()
             return qtawesome.icon("mdi.play") if playerState.isPlaying(
             ) else qtawesome.icon("mdi.pause") if playerState.isPaused(
             ) else qtawesome.icon()
コード例 #6
0
 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)
コード例 #7
0
ファイル: models.py プロジェクト: kwon-young/pyqt_corrector
    def data(self, index: QModelIndex, role):
        """Get data at given index"""
        if not index.isValid():
            return None

        if self._data is None:
            return None

        if role == Qt.DisplayRole:
            return self._data.iloc[index.row()][index.column()]
        if role == Qt.UserRole:
            page = self._data["page"][index.row()]
            tableData = self._data.query(f"page == '{page}'").copy()
            tableData["box"] = tableData["box"].apply(box2QRect)
            return tableData
        return None
コード例 #8
0
ファイル: taskgroups.py プロジェクト: renaudll/csp4cg
    def setData(self, index: QModelIndex, value: Any, role: int = Qt.EditRole) -> bool:
        if role == TasksGroupWeightRole:
            self._context.combinations[index.row()].weight = int(value)
            self.dataChanged.emit(index, index, [role])
            return True

        raise NotImplementedError(f"setData not implemented for role {role}")
コード例 #9
0
ファイル: main_menu_model.py プロジェクト: abud995/Restoran
    def get_element(self, index: QtCore.QModelIndex):

        if index.isValid():
            element = self._data[index.row()][index.column()]
            if element:
                return element
        return None
コード例 #10
0
    def data(  # type: ignore
            self,
            index: QModelIndex,
            role: int,
    ) -> Any:
        """
        Get data at the given index for the given role.

        Args:
            index: a data index
            role: a data role

        Returns:
            The data
        """
        return_conditions = (
            self._exportable_dict is None,
            not index.isValid(),
            index.column() not in {0, 1},
        )
        if any(return_conditions):
            return None
        if role in {Qt.DisplayRole, Qt.EditRole}:
            data = [
                list(self._exportable_dict.keys()),
                list(self._exportable_dict.values()),
            ]
            return data[index.column()][index.row()]
        return None
コード例 #11
0
ファイル: change_branch.py プロジェクト: Roy-043/FreeCAD
 def data(self,
          index: QtCore.QModelIndex,
          role: int = QtCore.Qt.DisplayRole):
     if not index.isValid():
         return None
     row = index.row()
     column = index.column()
     if role == QtCore.Qt.ToolTipRole:
         tooltip = ""
         # TODO: What should the tooltip be for these items? Last commit message?
         return tooltip
     elif role == QtCore.Qt.DisplayRole:
         dd = self.display_data[row]
         if column == 3 or column == 4:
             if dd[column] is not None:
                 qdate = QtCore.QDateTime.fromTime_t(dd[column])
                 return QtCore.QLocale().toString(
                     qdate, QtCore.QLocale.ShortFormat)
         elif column < len(dd):
             return dd[column]
         else:
             return None
     elif role == ChangeBranchDialogModel.DataSortRole:
         if column == 0:
             if self.refs[row] in self.repo.heads:
                 return 0
             else:
                 return 1
         elif column < len(self.display_data[row]):
             return self.display_data[row][column]
         else:
             return None
     elif role == ChangeBranchDialogModel.RefAccessRole:
         return self.refs[row]
コード例 #12
0
 def get_from_idx(self, index: QtCore.QModelIndex):
     """Gets item from QModelIndex."""
     if not index.isValid():
         return None, None
     item = self.original_items[index.row()]
     key = self.properties[index.column()]
     return item, key
コード例 #13
0
    def data(self, index: QModelIndex, role: Qt.ItemDataRole = Qt.DisplayRole):
        """Return data for corresponding index and role.

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

        Returns:
            ojbect: The data
        """
        self._index = index
        row = index.row()
        column = index.column()

        if role == Qt.DisplayRole:
            if column == 0:
                return str(list(self._data.keys())[row])
            elif column == 1:
                return str(self._data[list(self._data.keys())[row]])
            elif column == 2:
                return str(
                    self.design.parse_value(self._data[list(
                        self._data.keys())[row]]))

        # double clicking
        elif role == Qt.EditRole:
            return self.data(index, Qt.DisplayRole)

        elif (role == Qt.FontRole) and (column == 0):
            font = QFont()
            font.setBold(True)
            return font
コード例 #14
0
    def data(self, index: QModelIndex, role: int):
        if not index.isValid() or role not in (Qt.DisplayRole, Qt.EditRole,
                                               Qt.TextAlignmentRole):
            return

        col = index.column()
        row = index.row()

        if role == Qt.TextAlignmentRole:
            if col > 2:
                return Qt.AlignRight
            return Qt.AlignLeft

        if col == 0:
            item_id = self.get_item_id(row)
            count = self.selected[
                item_id].count if item_id in self.selected else 0
            if role == Qt.DisplayRole:
                return str(count)
            else:
                return count
        elif col == 4:
            return f"{self.sourceModel().data(index.sibling(index.row(), 5), role):.2f}"
        else:
            return self.sourceModel().data(index, role)
コード例 #15
0
    def data(self, index: QModelIndex, role: int = ...) -> typing.Any:
        if not index.isValid():
            return None

        row = index.row()
        col = index.column()

        if role == Qt.UserRole:
            return self.list[row].id

        if role == Qt.TextAlignmentRole:
            if col > 1:
                return Qt.AlignRight
            return Qt.AlignLeft

        if role == Qt.BackgroundRole and self.ex is not None and row < len(
                self.list):
            if self.ex.casefold() in self.list[row].code.casefold() or (
                    self.ex and self.ex == self.list[row].discount_group):
                return QColor(0xFC, 0xF7, 0xBB)

        if role == Qt.EditRole and row < len(self.list) and col in (3, 5):
            return self.list[row][col]

        if role == Qt.DisplayRole:
            if row == len(self.list):
                if col == 6:
                    return self.tr("Total:")
                elif col == 7:
                    return f"{self.grand_total:.20n}"
            elif row < len(self.list):
                return self.list[row].formatted_field(col)
コード例 #16
0
    def data(self, index: QtCore.QModelIndex, role: QtCore.Qt) -> Any:
        if role == QtCore.Qt.CheckStateRole and index.column() == 0:
            checked = self.headers[index.row()][0]
            if checked:
                return QtCore.Qt.Checked
            else:
                return QtCore.Qt.Unchecked

        if role == QtCore.Qt.DisplayRole or role == QtCore.Qt.EditRole:
            if not index.isValid():
                return None

            if index.row() > len(self.headers) or index.column() == 0:
                return None

            return self.headers[index.row()][index.column()]
コード例 #17
0
    def data(self,
             index: qc.QModelIndex = qc.QModelIndex(),
             role: int = qq.DisplayRole) -> t.Any:
        if not index.isValid():
            return None

        one = index.row()
        two = index.column()
        result = self._results.get((one, two))

        if not result:
            if qq.BackgroundRole == role:
                if one == two:
                    return qg.QColor.fromRgbF(0, 0, 0, 0.4)
                else:
                    return qg.QColor.fromRgbF(0, 0, 0, 0.2)

            elif qq.ToolTipRole == role:
                return 'Не сравнивается'

        else:
            if qq.TextAlignmentRole == role:
                return qq.AlignCenter

            if PragmaticAdequacyResult.WORKING == result.state:
                if qq.DisplayRole == role:
                    return '...'
                elif qq.BackgroundRole == role:
                    return Colors.BG_ORANGE
            elif PragmaticAdequacyResult.SUCCESS == result.state:
                if qq.DisplayRole == role:
                    return str(result.value)
コード例 #18
0
ファイル: main.py プロジェクト: yenru0/antanswer
 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)
コード例 #19
0
    def data(self, QModelIndex, role=None):
        row = QModelIndex.row()
        if role == self.FilenameRole:
            return str(self._pictures[row][0])

        if role == self.CaptionRole:
            return str(self._pictures[row][1])
コード例 #20
0
 def data(self, index: QModelIndex, role: int = None):
     if not index.isValid():
         return None
     if role == Qt.DisplayRole:
         return self.getValue(index.row(), index.column())
     elif role == Qt.TextAlignmentRole:
         v = self.getValue(index.row(), index.column())
         if isinstance(v, numbers.Number):
             return int(Qt.AlignRight | Qt.AlignVCenter)
     elif role == Qt.ForegroundRole:
         return self._getForegroundBrush(index.row(), index.column())
     elif role == Qt.BackgroundRole:
         return self._getBackgroundBrush(index.row(), index.column())
     elif role == Qt.FontRole:
         return self._getFont(index.row(), index.column())
     return None
コード例 #21
0
    def setData(self,
                index: QModelIndex,
                value: str,
                role: Qt.ItemDataRole = Qt.EditRole) -> bool:
        """Modify either key or value (Property or Value) of dictionary
        depending on what the user selected manually on the table.

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

        Returns:
            bool: True if successful; otherwise returns False.
        """
        r = index.row()
        c = index.column()

        if value:

            if c == 0:
                # TODO: LRU Cache for speed?
                oldkey = list(self._data.keys())[r]
                if value != oldkey:
                    self.design.rename_variable(oldkey, value)
                    self._gui.rebuild()
                    return True

            elif c == 1:
                self._data[list(self._data.keys())[r]] = value
                self._gui.rebuild()
                return True

        return False
コード例 #22
0
 def data(self, index: QModelIndex, role=...) -> 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)
     return None
コード例 #23
0
    def data(self, index: QtCore.QModelIndex, role=QtCore.Qt.DisplayRole):
        """Overrides Qt method, returns data for given row."""
        if role == QtCore.Qt.DisplayRole and index.isValid():
            idx = index.row()
            return self._node_list[idx]

        return None
コード例 #24
0
    def data(self, index: QModelIndex, role: int = Qt.DisplayRole) -> Any:
        row = index.row()
        task = self._context.tasks[row]
        if role in (Qt.DisplayRole, Qt.EditRole, RoleTaskName):
            return task.name
        if role == Qt.UserRole:
            return task
        if role == RoleTaskDuration:
            return str(task.duration.total_seconds() / 60 / 60)  # hours
        if role == RoleTaskWidth:
            return task.duration.total_seconds() / 60 / 60  # hours
        if role == RoleTaskTags:
            return ",".join(task.tags)
        if role == RoleTaskLocked:
            return any(assignment.task == task
                       for assignment in self._context.assignments)
        if role in (
                RoleTaskXCoord,
                RoleTaskYCoord,
                RoleTaskArtist,
                RoleAssignment,
        ):
            try:
                return self._extra_roles[row][role]
            except (IndexError, KeyError):  # cache need to be regenerated
                self.resetInternalData()
            return self._extra_roles[row][role]

        return None
コード例 #25
0
 def data(self, index: QtCore.QModelIndex, role: int = ...) -> typing.Any:
     playlist = self._player.getPlaylists()[index.row()]
     if role == QtCore.Qt.DisplayRole:
         if index.column() == 0:
             return playlist.name
         elif index.column() == 1:
             return str(len(playlist.musics))
コード例 #26
0
 def paint(self, painter: QPainter, option: QStyleOptionViewItem,
           index: QModelIndex):
     pixmap = self.get_pixmap(option, index)
     if not pixmap.isNull():
         view = option.styleObject
         view.setRowHeight(index.row(), pixmap.height())
         painter.drawImage(option.rect, pixmap)
コード例 #27
0
 def move_drop(self, destination_index: QModelIndex):
     if not self.view.supports_drag_move:
         return
     LOGGER.debug('Drop with MoveAction at Proxy @%sP%s',
                  destination_index.row(),
                  destination_index.parent().row())
     self.view.editor.move_rows(destination_index)
コード例 #28
0
    def data(  # type: ignore
            self,
            index: QModelIndex,
            role: int,
    ) -> Any:
        """
        Get data at the given index for the given role.

        Args:
            index: a data index
            role: a data role

        Returns:
            The data
        """
        return_conditions = (
            self._exportable_list is None,
            not index.isValid(),
            index.column() != 0,
        )
        if any(return_conditions):
            return None
        if role in {Qt.DisplayRole, Qt.EditRole}:
            return self._exportable_list[index.row()]
        return None
コード例 #29
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)
コード例 #30
0
ファイル: open_files_model.py プロジェクト: thane98/paragon
 def data(self, index: QModelIndex, role: int = ...) -> Any:
     if not index.isValid():
         return None
     (key, value) = self._get_elem(index.row())
     if role == QtCore.Qt.DisplayRole:
         return key
     return None