如何在没有元类冲突的情况下对PyQt子类使用泛型类型?

use*_*126 7 python metaclass typing pyqt5 pyside2

我曾尝试abc.ABCMeta使用sip包装器类型,并且在子类使用时效果很好abc.ABC.

class QABCMeta(wrappertype, ABCMeta):
    pass

class WidgetBase(QWidget, metaclass=QABCMeta):
    ...

class InterfaceWidget(WidgetBase, ABC):
    ...

class MainWidget(InterfaceWidget):
    ...
Run Code Online (Sandbox Code Playgroud)

但它不起作用typing.Generic.

class QGenericMeta(wrappertype, GenericMeta):
    pass

class WidgetBase(QWidget, Generic[T], metaclass=QGenericMeta):
    ...

class GenericWidget(WidgetBase[float]):
    ...
Run Code Online (Sandbox Code Playgroud)

它提出:

line 980, in __new__
    self if not origin else origin._gorg)
TypeError: can't apply this __setattr__ to sip.wrappertype object
Run Code Online (Sandbox Code Playgroud)

我希望它像往常一样使用泛型子类:

class TableBase(QTableWidget, Generic[T]):
    @abstractmethod
    def raw_item(self, row: int) -> T:
        ...
    def data(self) -> Iterator[T]:
        yield from (self.raw_item(row) for row in range(self.rowCount()))

class MainTable(TableBase[float]):
    def raw_item(self, row: int) -> float:
        return float(self.item(row, 1).text())  # implementation

table = MainTable()
for data in table.data():
    data: float
Run Code Online (Sandbox Code Playgroud)

但是data仍然Any没有继承权Generic[T].

可以通过PEP 560解决类型检查吗?

use*_*126 7

嗯,我找到了答案。

由于typing.Genericis的元类abc.ABC,它也应该基于abc.ABCMeta。但这仅适用于 Python 3.7 或更高版本。

然后,只需使用type(QObject)代替sip.wrappertype

# -*- coding: utf-8 -*-

from abc import abstractmethod, ABC, ABCMeta
from typing import TypeVar, Generic, Iterator
from PyQt5.QtCore import QObject
from PyQt5.QtWidgets import QTableWidget

QObjectType = type(QObject)
T = TypeVar('T')


class QABCMeta(QObjectType, ABCMeta):
    pass


class BaseWidget(QTableWidget, Generic[T], metaclass=QABCMeta):

    @abstractmethod
    def raw_item(self, row: int) -> T:
        ...

    def data(self) -> Iterator[T]:
        yield from (self.raw_item(row) for row in range(self.rowCount()))


class TestWidget(BaseWidget[float], ABC):  # optional inherit ABC.

    def raw_item(self, row: int) -> float:
        return float(self.item(row, 1).text())


if __name__ == '__main__':
    w = TestWidget()
    for f in w.data():
        pass
Run Code Online (Sandbox Code Playgroud)

此代码适用于 PyCharm IDE,变量的注释ffloat.

当更改PyQt5为 时PySide2,它也有效!