Define a protocol that mimics QFileSystemModel.index() and its overloads

65 views Asked by At

I'm trying to implement a protocol that mimics QFileSystemModel so that I can use that protocol to define a new custom class. The protocol definition is generating a mypy error when trying to make sure that protocol is satisfied by current QFileSystemModel derived class. Here is what I've tried...

import typing
from PyQt6 import QtCore, QtGui


class FileSystemModelProtocol(typing.Protocol):
    """Define the subset of QFileSystemModel methods used...for defining a class with the same behavior"""
    @typing.overload
    def index(self, row: int, column: int, parent: QtCore.QModelIndex = ...) -> QtCore.QModelIndex: ...
    @typing.overload
    # def index(self, path: typing.Optional[str], column: int = ...) -> QtCore.QModelIndex: ... path vs row causes an error
    def index(self, row: typing.Optional[str], column: int = ...) -> QtCore.QModelIndex: ...
    def index(self, row: typing.Optional[int | str] = ..., column: int = ..., parent: QtCore.QModelIndex = ...) -> QtCore.QModelIndex: ...


class CustomFileSystemModel(QtGui.QFileSystemModel, FileSystemModelProtocol):  # error: Definition of "index" in base class "QAbstractItemModel" is incompatible with definition in base class "FileSystemModelProtocol"
    pass


class TableModel(QtCore.QAbstractTableModel, FileSystemModelProtocol):
    def index_from_str(self, path: str) -> QtCore.QModelIndex:
        return QtCore.QModelIndex()  # TODO: lookup with path

    def index(self, row_path: typing.Optional[int | str] = None, column: int = 0, parent: QtCore.QModelIndex = QtCore.QModelIndex()) -> QtCore.QModelIndex:
        if isinstance(row_path, str):
            return self.index_from_str(row_path)
        if isinstance(row_path, int):
            return super().index(row_path, column, parent)
        return QtCore.QModelIndex()


c = CustomFileSystemModel()
t = TableModel()

*** Edited down to a more minimal example. The previous edit showed some previous attempts as well as the relevant prototypes from the qt sources. This should be just the relevant code. Mypy execution and results follow

*** Edit 2 Renaming path in the second overload to row made this error go away ...# error: Overloaded function implementation does not accept all possible arguments of signature 2

mypy file_system_protocol_test_so1.py 
file_system_protocol_test_so1.py:26: error: Definition of "index" in base class "QAbstractItemModel" is incompatible with definition in base class "FileSystemModelProtocol"  [misc]
Found 1 error in 1 file (checked 1 source file)
0

There are 0 answers