使用 PySide2 在 QML 中注册类型 [英] Registering a type in QML using PySide2
问题描述
我正在尝试使用 Python 创建新的 QML 类型,但在注册 QML 类型时遇到问题.但是,我收到一个错误:
I am trying to create a new QML type by using Python, but I am having trouble with registering a QML type. 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)
所以我知道它期待一种类型,但是,在这个 blogpost 它做了类似的事情:
So I understand that its expecting a type, however, in this blogpost it does something similar:
qmlRegisterType(PieChart, 'Charts', 1, 0, 'PieChart')
这让我很困惑,我不知道自己做错了什么?
在我的 main.py 中,我有这个:
Which leaves me confused, I don't know what I'm doing wrong?
In my main.py, I have this:
...
if __name__ == '__main__':
# Declare QApplication
app=QApplication([])
qmlRegisterType(CamFeed, 'CFeed', 1, 0, 'CamFeed')
...
CamFeed.py 看起来像这样:
CamFeed.py looks like this:
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 的:
Surely in the main.py file you are importing the CamFeed.py in the following way:
import CamFeed
if __name__ == '__main__':
# Declare QApplication
app = QApplication([])
qmlRegisterType(CamFeed, 'CFeed', 1, 0, 'CamFeed')
在这种情况下,CamFeed 是模块(.py 文件),因此有两种解决方案:
In that case CamFeed is the module (.py file), so there are 2 solutions:
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')
<小时>
另一方面,按照约定小写的名称:
On the other hand by convention the name of the lowercase:
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')
这篇关于使用 PySide2 在 QML 中注册类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!