简体   繁体   English

使用 PySide2 在 QML 中注册类型

[英]Registering a type in QML using PySide2

I am trying to create a new QML type by using Python, but I am having trouble with registering a QML type.我正在尝试使用 Python 创建新的 QML 类型,但在注册 QML 类型时遇到问题。 However, I am getting an Error:但是,我收到一个错误:

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)

So I understand that its expecting a type, however, in this blogpost it does something similar:所以我知道它期待一种类型,但是,在这篇博文中它做了类似的事情:

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

Which leaves me confused, I don't know what I'm doing wrong?这让我很困惑,我不知道我做错了什么?

In my main.py, I have this:在我的 main.py 中,我有这个:

...

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

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

    ...

CamFeed.py looks like this: 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)

Surely in the main.py file you are importing the CamFeed.py in the following way:当然,在 main.py 文件中,您正在通过以下方式导入 CamFeed.py:

import CamFeed

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

In that case CamFeed is the module (.py file), so there are 2 solutions:在这种情况下,CamFeed 是模块(.py 文件),因此有两种解决方案:

1. 1.

from CamFeed import CamFeed

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

2. 2.

import CamFeed

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

On the other hand by convention the name of the lowercase:另一方面,按照约定小写的名称:

camfeed.py 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')

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

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