Skip to content

StandardItemModel

Base classes

Name Children Inherits
AbstractItemModelMixin
prettyqt.core.abstractitemmodel
QStandardItemModel
PySide6.QtGui
QStandardItemModel(self, /, parent: PySide6.QtCore.QObject | None \= None, *, sortRole: int | None \= None) -> None

â‹” Inheritance diagram

graph TD
  1603772148["gui.StandardItemModel"]
  3882849576["core.AbstractItemModelMixin"]
  3227531497["core.ObjectMixin"]
  2751680898["builtins.object"]
  2398987522["QtGui.QStandardItemModel"]
  1898060022["QtCore.QAbstractItemModel"]
  3984060476["QtCore.QObject"]
  37984305["Shiboken.Object"]
  3882849576 --> 1603772148
  3227531497 --> 3882849576
  2751680898 --> 3227531497
  2751680898 --> 3882849576
  2398987522 --> 1603772148
  1898060022 --> 2398987522
  3984060476 --> 1898060022
  37984305 --> 3984060476
  2751680898 --> 37984305

🛈 DocStrings

Bases: AbstractItemModelMixin, QStandardItemModel

Source code in prettyqt/gui/standarditemmodel.py
class StandardItemModel(core.AbstractItemModelMixin, gui.QStandardItemModel):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.setItemPrototype(gui.StandardItem())

    def __getitem__(
        self, index: int | slice | tuple[int | slice, int | slice] | core.QModelIndex
    ) -> gui.QStandardItem | listdelegators.ListDelegator[gui.QStandardItem]:
        rowcount = self.rowCount()
        colcount = self.columnCount()
        match index:
            case int() as row:
                if row < 0:
                    row = row + rowcount
                if row < 0 or row >= rowcount:
                    raise IndexError(index)
                return self.item(row)
            case slice():
                return self.__getitem__((index, 0))
            case core.QModelIndex():
                return self.itemFromIndex(index)
            case int() as row, int() as col:
                if row < 0:
                    row = row + rowcount
                if col < 0:
                    col = col + colcount
                return self.item(row, col)
            case (row, col):
                items = [
                    self.item(i, j)
                    for i, j in helpers.iter_positions(row, col, rowcount, colcount)
                ]
                return listdelegators.ListDelegator(items)
            case _:
                raise TypeError(index)

    def __delitem__(self, index: int | tuple[int, int]):
        match index:
            case int():
                item = self.takeRow(index)
            case (int(), int()):
                item = self.takeItem(*index)
            case _:
                raise TypeError(index)
        if not item:
            raise KeyError(index)
        return item

    def __iter__(self) -> Iterator[gui.QStandardItem]:
        return iter(self.get_children())

    def __getstate__(self):
        return dict(items=[self.item(index) for index in range(self.rowCount())])

    def __setstate__(self, state):
        for item in state["items"]:
            self.appendRow([item])

    def __reduce__(self):
        return type(self), (), self.__getstate__()

    def __add__(self, other: str | gui.QStandardItem) -> StandardItemModel:
        match other:
            case gui.QStandardItem() | str():
                self.add(other)
                return self
            case _:
                msg = "wrong type for addition"
                raise TypeError(msg)

    def get_children(self) -> listdelegators.ListDelegator[gui.QStandardItem]:
        items = [self.item(index) for index in range(self.rowCount())]
        return listdelegators.ListDelegator(items)

    def add(self, *item: str | gui.QStandardItem):
        for i in item:
            new_item = gui.StandardItem(i) if isinstance(i, str) else i
            self.appendRow([new_item])

    def find_items(
        self,
        text: str,
        column: int = 0,
        mode: constants.MatchFlagStr | constants.MatchFlag = "exact",
        recursive: bool = False,
        case_sensitive: bool = False,
    ) -> listdelegators.ListDelegator[gui.QStandardItem]:
        flag = constants.MATCH_FLAGS.get_enum_value(mode)
        if recursive:
            flag |= constants.MatchFlag.MatchRecursive
        if case_sensitive:
            flag |= constants.MatchFlag.MatchCaseSensitive
        items = self.findItems(text, flag, column)
        return listdelegators.ListDelegator(items)

    def add_item(
        self,
        name: str = "",
        icon: datatypes.IconType = None,
        data: dict | None = None,
        foreground: gui.QBrush | None = None,
        background: gui.QBrush | None = None,
        font: gui.QFont | None = None,
        selectable: bool | None = None,
        enabled: bool | None = None,
        editable: bool | None = None,
        status_tip: str = "",
        tool_tip: str = "",
        whats_this: str | None = None,
        # text_alignment: Optional[str] = None,
        checkstate: constants.CheckStateStr | None = None,
        flags: constants.ItemFlag | None = None,
        size_hint: datatypes.SizeType | None = None,
        is_user_type: bool = False,
    ) -> gui.StandardItem:
        item = gui.StandardItem(name)
        if icon is not None:
            icon = iconprovider.get_icon(icon)
            item.setIcon(icon)
        if data is not None:
            for k, v in data.items():
                item.set_data(v, k)
        if foreground is not None:
            item.setForeground(foreground)
        if background is not None:
            item.setBackground(background)
        if font is not None:
            item.setFont(font)
        if flags is not None:
            item.setFlags(flags)
        if enabled is not None:
            item.setEnabled(enabled)
        if editable is not None:
            item.setEditable(editable)
        if selectable is not None:
            item.setSelectable(selectable)
        if status_tip:
            item.setStatusTip(status_tip)
        if tool_tip:
            item.setToolTip(tool_tip)
        if whats_this:
            item.setWhatsThis(whats_this)
        if size_hint is not None:
            item.set_size_hint(size_hint)
        if checkstate is not None:
            item.set_checkstate(checkstate)
        self.appendRow([item])
        return item

    @classmethod
    def from_dict(cls, dct: dict, **kwargs):
        model = cls(**kwargs)
        model.setHorizontalHeaderLabels(list(dct.keys()))
        for column, v in enumerate(dct.values()):
            for row, label in enumerate(v):
                item = gui.StandardItem(str(label))
                item.setData(label, constants.EDIT_ROLE)
                model.setItem(row, column, item)
        return model

:fa-brands-github: Show source on GitHub