繁体   English   中英

使用 PySide2 在 QML 中注册类型

[英]Registering a type in QML using 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)

所以我知道它期待一种类型,但是,在这篇博文中它做了类似的事情:

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)

当然,在 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)

主文件

from camfeed import CamFeed

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM