QQuickImageProvider PyQt5

时间:2017-11-27 01:40:24

标签: python qml pyqt5

我尝试使用 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,我不知道我有什么问题。

2 个答案:

答案 0 :(得分: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"
    }
}

答案 1 :(得分:0)

我有同样的问题。似乎是因为提供程序实例传递到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()