使用PySide2在QML中注册类型

2024-09-30 16:19:37 发布

您现在位置: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中,它做了类似的事情:

^{pr2}$

这让我很困惑,我不知道我做错了什么?在

在我的主.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)


Tags: frompyimport类型initdefqmlint
1条回答
网友
1楼 · 发布于 2024-09-30 16:19:37

当然是在主.py要导入的文件CamFeed.py通过以下方式:

import CamFeed

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

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

1.

^{pr2}$

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)

主.py

from camfeed import CamFeed

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

相关问题 更多 >