使用PySide2在QML中注册类型

时间:2019-04-05 01:36:18

标签: python python-3.x pyside2

我正在尝试使用Python创建新的QML类型,但是在注册QML类型时遇到了麻烦。但是,我得到一个错误:

TypeError: 'PySide2.QtQml.qmlRegisterType' called with wrong argument types:
  PySide2.QtQml.qmlRegisterType(module, str, int, int, str)
Supported signatures:
  PySide2.QtQml.qmlRegisterType(type, str, int, int, str)

因此,我知道它期望一个类型,但是,在此blogpost中,它执行类似的操作:

qmlRegisterType(PieChart, 'Charts', 1, 0, 'PieChart')

这让我感到困惑,我不知道我在做什么错?

在我的main.py中,我有这个:

...

if __name__ == '__main__':
    # Declare QApplication
    app=QApplication([])

    qmlRegisterType(CamFeed, 'CFeed', 1, 0, 'CamFeed')

    ...

CamFeed.py看起来像这样:

from PySide2.QtQuick import QQuickPaintedItem
from PySide2.QtGui import QPainter
from PySide2.QtCore import QObject

class CamFeed(QQuickPaintedItem):
    def __init__(self, parent=None):
        super().__init__(parent)

    # Re-implementation of the virtual function
    def paint(self, painter):
        painter.drawRect(10,10,50,50)

1 个答案:

答案 0 :(得分:1)

肯定是在main.py文件中,您通过以下方式导入CamFeed.py:

import CamFeed

if __name__ == '__main__':
    # Declare QApplication
    app = QApplication([])
    qmlRegisterType(CamFeed, 'CFeed', 1, 0, 'CamFeed')

在这种情况下,CamFeed是模块(.py文件),因此有两种解决方案:

1。

from CamFeed import CamFeed

if __name__ == '__main__':
    # Declare QApplication
    app = QApplication([])
    qmlRegisterType(CamFeed, 'CFeed', 1, 0, 'CamFeed')

2。

import CamFeed

if __name__ == '__main__':
    # Declare QApplication
    app = QApplication([])
    qmlRegisterType(CamFeed.CamFeed, 'CFeed', 1, 0, 'CamFeed')

另一方面,按照惯例,小写字母的名称:

camfeed.py

from PySide2.QtQuick import QQuickPaintedItem
from PySide2.QtGui import QPainter
from PySide2.QtCore import QObject

class CamFeed(QQuickPaintedItem):
    def __init__(self, parent=None):
        super().__init__(parent)

    # Re-implementation of the virtual function
    def paint(self, painter):
        painter.drawRect(10,10,50,50)

main.py

from camfeed import CamFeed

if __name__ == '__main__':
    # Declare QApplication
    app = QApplication([])
    qmlRegisterType(CamFeed, 'CFeed', 1, 0, 'CamFeed')