Skip to main content
 首页 » 编程设计

python之PyQt5:派生 QWidget 类中带有元类的 Mixin 的问题

2024年10月01日8webabcd

我在尝试将带有元类的混合添加到基类为 QWidget 的类时遇到问题。我知道 PyQt5 supports cooperative multiple inheritance如果我的 MixIn 类没有元类,那么一切正常。但是,如果它有元类——无论是 QWidgets 共享的 pyqtWrapperType 元类还是派生的元类,我都会收到以下错误:

进程已完成,退出代码为 -1073741819 (0xC0000005)

脚本其余部分的代码运行,但 QWidget 不显示。这是基本代码(去掉了方法,因为我知道它们不是问题所必需的)

import abc, sys 
from PyQt5 import QtWidgets, QtCore 
 
# Test Metaclass, will have more if metaclasses work 
class MyMeta(abc.ABCMeta, QtCore.pyqtWrapperType): 
    def __init__(cls, name, bases, attrs): 
        super(MyMeta, cls).__init__(name, bases, attrs) 
 
# MixIn class - ignore the calls to methods for now 
# Have same issue if metaclass set to pyqtWrapperType 
class LocatorWidget(metaclass=MyMeta): 
    def __init__(self, locator=None, name='', parameters={}, **kwargs): 
        super().__init__(**kwargs) 
        # self.setup_parameters(parameters) 
        self.locator = locator 
        self.name = name if name else '' 
        self.widgetType = self.__class__.__name__.replace('LW', '') 
        # self.setup() 
 
# Derived class with a QWidget base 
class LWComboBox(QtWidgets.QComboBox, LocatorWidget): 
    def __init__(self, locator, **kwargs): 
        super().__init__(locator=locator, **kwargs) 
 
def main(): 
    app = QtWidgets.QApplication(sys.argv) 
    # locator is class in full code, using this as filler for now 
    locator=[0,1,2,3] 
    cb = LWComboBox(locator=locator) 
    cb.addItems([str(x) for x in range(5)]) 
    # Test to see if attribute is set 
    print(cb.locator) 
 
    window = QtWidgets.QDialog() 
    window.form = QtWidgets.QFormLayout() 
    window.form.addRow(cb) 
    window.setLayout(window.form) 
 
    window.show() 
 
if __name__ == '__main__': 
    main() 

我没有有元类冲突错误:基类和派生类没有不同的元类,因为 MyMeta 是从 pyqtWrapperType 派生的。

如果这个过程不起作用,我想知道我是否应该坚持我以前的想法,即用我想在一个单独的类中共享的属性和方法包围小部件,小部件是属性之一,但是使用必要的抽象方法和属性直接对 QWidgets 进行子类化会很好。

仅供引用,我在 Anaconda 中运行 PyCharm 2016.2.3,PyQt5 版本为 5.6(PyQt 无法更新到 Anaconda 中的更高版本)

请您参考如下方法:

pyqtWrapperType 不再存在。如果你想要 PyQt5 中的等效类型,你可以使用:

pyqtWrapperType = type(QtCore.QObject) 

或:

from sip import wrappertype as pyqtWrapperType