Skip to content

EditorDelegate

Qt Base Class: QStyledItemDelegate

Signature: QStyledItemDelegate(self, parent: Optional[PySide6.QtCore.QObject] = None) -> None

Base classes

Name Children Inherits
StyledItemDelegate
prettyqt.widgets.styleditemdelegate

⋔ Inheritance diagram

graph TD
  1473367015008["itemdelegates.EditorDelegate"]
  1473296354464["widgets.StyledItemDelegate"]
  1473296344704["widgets.AbstractItemDelegateMixin"]
  1473299815024["core.ObjectMixin"]
  140713234304496["builtins.object"]
  1473293727280["QtWidgets.QStyledItemDelegate"]
  1473293758512["QtWidgets.QAbstractItemDelegate"]
  1473288842240["QtCore.QObject"]
  1473291690208["Shiboken.Object"]
  1473296354464 --> 1473367015008
  1473296344704 --> 1473296354464
  1473299815024 --> 1473296344704
  140713234304496 --> 1473299815024
  1473293727280 --> 1473296354464
  1473293758512 --> 1473293727280
  1473288842240 --> 1473293758512
  1473291690208 --> 1473288842240
  140713234304496 --> 1473291690208

🛈 DocStrings

Bases: StyledItemDelegate

Delegate which supports editing a large range of data types.

Allows editing a large range of different types from Qt, builtin libraries as well as some Numpy types.

The Delegate also has an extended displayText method to show a repr-like string for different data types.

The following data types are supported:

  • bool
  • enum.Flag
  • enum.Enum
  • int
  • float
  • str
  • range
  • slice
  • list of ints
  • list of floats
  • list of strings
  • pathlib.Path
  • re.Pattern
  • datetime.date
  • datetime.time
  • datetime.datetime
  • QtCore.QRegularExpression
  • QtCore.QTime
  • QtCore.QDate
  • QtCore.QDateTime
  • QtCore.QPoint
  • QtCore.QPointF
  • QtCore.QRect
  • QtCore.QRectF
  • QtCore.QRection
  • QtCore.QKeyCombination
  • QtCore.QLocale
  • QtCore.QSize
  • QtCore.QSizeF
  • QtCore.QUrl
  • QtGui.QFont
  • QtGui.QKeySequence
  • QtGui.QPalette
  • QtGui.QColor
  • QtGui.QBrush
  • QtGui.QCursor
  • QtGui.QIcon
  • QtWidgets.QSizePolicy

If numpy is installed, the following types are supported, too:

  • numpy.floating
  • numpy.integer
  • numpy.str_
  • numpy.datetime64
  • numpy.bool_
Source code in prettyqt\itemdelegates\editordelegate.py
class EditorDelegate(widgets.StyledItemDelegate):
    """Delegate which supports editing a large range of data types.

    Allows editing a large range of different types from Qt, builtin libraries as well
    as some Numpy types.

    The Delegate also has an extended displayText method to show a repr-like string for
    different data types.

    The following data types are supported:

    * bool
    * enum.Flag
    * enum.Enum
    * int
    * float
    * str
    * range
    * slice
    * list of ints
    * list of floats
    * list of strings
    * pathlib.Path
    * re.Pattern
    * datetime.date
    * datetime.time
    * datetime.datetime
    * QtCore.QRegularExpression
    * QtCore.QTime
    * QtCore.QDate
    * QtCore.QDateTime
    * QtCore.QPoint
    * QtCore.QPointF
    * QtCore.QRect
    * QtCore.QRectF
    * QtCore.QRection
    * QtCore.QKeyCombination
    * QtCore.QLocale
    * QtCore.QSize
    * QtCore.QSizeF
    * QtCore.QUrl
    * QtGui.QFont
    * QtGui.QKeySequence
    * QtGui.QPalette
    * QtGui.QColor
    * QtGui.QBrush
    * QtGui.QCursor
    * QtGui.QIcon
    * QtWidgets.QSizePolicy

    If numpy is installed, the following types are supported, too:

    * numpy.floating
    * numpy.integer
    * numpy.str_
    * numpy.datetime64
    * numpy.bool_

    """

    ID = "editor"

    def __init__(
        self,
        *args,
        role: constants.ItemDataRole = constants.EDIT_ROLE,
        validator: gui.QValidator
        | widgets.lineedit.ValidatorStr
        | datatypes.PatternType
        | None = None,
        **kwargs,
    ):
        super().__init__(*args, **kwargs)
        self._role = role
        self._validator = validator

    def paint(
        self,
        painter: gui.QPainter,
        option: widgets.QStyleOptionViewItem,
        index: core.ModelIndex,
    ):
        # if not self.is_supported_type(value):
        #     option = widgets.StyleOptionViewItem(option)
        #     option.state &= ~widgets.QStyle.StateFlag.State_Enabled
        from prettyqt import itemdelegates

        match value := self._data_for_index(index, self._role):
            case gui.QIcon():
                icon_delegate = itemdelegates.IconDelegate()
                icon_delegate.paint(painter, option, index)
                return
            case enum.Enum():  # PySide6 needs this when using Views
                option.text = value.name
                option.widget.style().drawControl(
                    widgets.QStyle.ControlElement.CE_ItemViewItem, option, painter
                )
            case _:
                super().paint(painter, option, index)

    def createEditor(
        self,
        parent: widgets.QWidget,
        option: widgets.QStyleOptionViewItem,
        index: core.ModelIndex,
    ):
        val = self._data_for_index(index, self._role)
        logger.info(f"creating editor for {val!r}...")
        if isinstance(val, list):
            widget = datatypes.get_editor_for_value_list(val, parent)
        else:
            widget = datatypes.get_editor_for_value(val, parent)
        if widget is None:
            logger.warning(f"Could not find editor for {val!r} ({type(val)})")
            return None
        if self._validator and isinstance(
            widget, widgets.LineEdit | widgets.AbstractSpinBoxMixin
        ):
            widget.set_validator(self._validator, append=True)

        widget.setAutoFillBackground(True)
        widget.set_focus_policy("strong")
        return widget

    def setEditorData(self, editor: widgets.QWidget, index: core.ModelIndex):
        value = self._data_for_index(index, self._role)
        logger.info(f"setting data for {editor!r} to {value!r}")
        editor.set_value(value)

    def setModelData(
        self,
        editor: widgets.QWidget,
        model: core.QAbstractItemModel,
        index: core.ModelIndex,
    ):
        if (value := editor.get_value()) is not None:
            logger.info(f"setting data for {model!r} to {value!r}")
            model.setData(index, value, self._role)
            # self.closeEditor.emit(editor, self.EndEditHint.NoHint)
            self.commitData.emit(editor)

    def displayText(self, value: Any, locale: core.QLocale) -> str:
        return datatypes.to_string(value, locale)

⌗ Property table

Qt Property Type Doc
objectName QString

Delegate ID: editor