QQuickImageProvider PyQt5
Posted
技术标签:
【中文标题】QQuickImageProvider PyQt5【英文标题】: 【发布时间】:2017-11-27 01:40:24 【问题描述】:我尝试使用 QQuickImageProvider 将 QImage 发送到 QML,在 c++ Qt5.9.2 中一切正常,但我尝试使用 PyQt5(5.9.2) 的类似代码,QML 只是说错误: ImageProvider支持Image类型但没有实现requestImage(),其实我实现了requestImage(),这里是我的代码:
main.py:
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtQml import *
from PyQt5.QtQuick import *
class MyImageProvider(QQuickImageProvider):
def __init__(self):
super(MyImageProvider, self).__init__(QQuickImageProvider.Image)
def requestImage(self, p_str, size):
img = QImage(300, 300, QImage.Format_RGBA8888)
img.fill(Qt.red)
return img, img.size()
app = QGuiApplication([])
viewer = QQuickView()
viewer.engine().addImageProvider("myprovider", MyImageProvider())
viewer.setResizeMode(QQuickView.SizeRootObjectToView)
viewer.setSource(QUrl("example.qml"))
viewer.show()
app.exec()
example.qml:
import QtQuick 2.7
Item
id: root
width: 800
height: 600
Image
// width: 300
// height: 300
source: "image://myprovider/test.png"
也许 requestImage() 在 python 和 c++ 中有不同的参数和返回值,我确定格式是正确的。参考一些例子,http://nullege.com/codes/search/PyQt5.QtQuick.QQuickImageProvider,我不知道我怎么了。
【问题讨论】:
【参考方案1】:根据我正在审查的问题是 QQuickView 或 QQmlEngine,这些类已过时。
我推荐你使用QQmlApplicationEngine:
main.py
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtQml import *
from PyQt5.QtQuick import *
class MyImageProvider(QQuickImageProvider):
def __init__(self):
super(MyImageProvider, self).__init__(QQuickImageProvider.Image)
def requestImage(self, p_str, size):
img = QImage(300, 300, QImage.Format_RGBA8888)
img.fill(Qt.red)
return img, img.size()
if __name__ == '__main__':
app = QGuiApplication(sys.argv)
engine = QQmlApplicationEngine()
engine.addImageProvider("myprovider", MyImageProvider())
engine.load(QUrl.fromLocalFile("example.qml"))
if len(engine.rootObjects()) == -1:
sys.exit(-1)
sys.exit(app.exec_())
example.qml
import QtQuick 2.7
import QtQuick.Window 2.2
Window
visible: true
width: 640
height: 480
Image
anchors.fill : parent
source: "image://myprovider/test.png"
【讨论】:
【参考方案2】:我遇到了同样的问题。似乎是因为提供者实例在传递给 addImageProvider() 后丢失了。我解决了这个问题,如下所示。
app = QGuiApplication([])
viewer = QQuickView()
provider = MyImageProvider() # keep this instance during your app running
viewer.engine().addImageProvider("myprovider", provider)
viewer.setResizeMode(QQuickView.SizeRootObjectToView)
viewer.setSource(QUrl("example.qml"))
viewer.show()
app.exec()
【讨论】:
以上是关于QQuickImageProvider PyQt5的主要内容,如果未能解决你的问题,请参考以下文章
使用 QQuickImageProvider 的正确方法是啥?
通过按钮单击触发带有参数的 QQuickImageProvider::requestImage()