QQuickImageProvider PyQt5 [英] QQuickImageProvider PyQt5
问题描述
我尝试使用 QQuickImageProvider 将 QImage 发送到 QML,在 C++ Qt5.9.2 中一切正常,但我尝试使用 PyQt5(5.9.2) 进行类似代码,QML 只是说错误:ImageProvider支持Image类型但是没有实现requestImage(),但实际上我实现了requestImage(),这里是我的代码:
I try to use QQuickImageProvider send QImage to QML, everything work well in c++ Qt5.9.2,but I try similar code with PyQt5(5.9.2), QML just says error:ImageProvider supports Image type but has not implemented requestImage(),but in fact,I implemented the requestImage(),here my code:
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,我不知道我怎么了.
Perhaps requestImage() has different parameters and return values in python and c++,I'm sure that's right in format. refer to some examples, http://nullege.com/codes/search/PyQt5.QtQuick.QQuickImageProvider, I don't know what's wrong with me.
推荐答案
根据我正在审查的问题是 QQuickView 或 QQmlEngine,这些类已经过时了.
According to what I'm reviewing the problem is QQuickView or QQmlEngine, these classes are obsolete.
我推荐你使用 QQmlApplicationEngine:
I recommend you use 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"
}
}
这篇关于QQuickImageProvider PyQt5的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!