PyQt5:在派生的QWidget类

时间:2017-03-15 22:47:20

标签: python pyqt5 multiple-inheritance mixins metaclass

我在尝试将带有元类的mixin添加到基类为QWidget的类时遇到问题。我知道PyQt5 supports cooperative multiple inheritance,如果我的MixIn类没有元类,那么事情就可以了。但是,如果它有一个元类 - 无论是QWidgets共享的pyqtWrapperType元类还是派生元类,我收到以下错误:

Process finished with exit code -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中使用PyQt5版本5.6运行PyCharm 2016.2.3(PyQt无法更新到Anaconda的更高版本)

1 个答案:

答案 0 :(得分:1)

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

pyqtWrapperType = type(QtCore.QObject)

或:

from sip import wrappertype as pyqtWrapperType