PyQt6 adding image resource to QDocument

568 Views Asked by At

I am porting an application from PyQT5 to PyQt6. It displays multiple images in a QTextEdit. I need to add an image resource to QTextEdit QTextDocument but am getting an error.

TypeError: addResource(self, int, QUrl, Any): argument 1 has unexpected type 'ResourceType'

Method variables are img: Dictionary, counter: Integer, text_edit: QTextEdit

path_ = self.app.project_path
if img['mediapath'][0] == "/":
    path_ = path_ + img['mediapath']
else:
     path_ = img['mediapath'][7:]
document = text_edit.document()
image = QtGui.QImageReader(path_).read()
image = image.copy(img['x1'], img['y1'], img['width'], img['height'])
# Need unique image names or the same image from the same path is reproduced
imagename = self.app.project_path + '/images/' + str(counter) + '-' + img['mediapath']
url = QtCore.QUrl(imagename)
document.addResource(QtGui.QTextDocument.ResourceType.ImageResource, url, QtCore.QVariant(image))

The Qt6 documentation at https://doc.qt.io/qt-6/qtextdocument.html#addResource says:

For example, you can add an image as a resource in order to reference it from within the document:

document->addResource(QTextDocument::ImageResource,
    QUrl("mydata://image.png"), QVariant(image));

Note: I have tried the following which matches the Qt6 documentation:

document.addResource(QtGui.QTextDocument.ImageResource, url, QtCore.QVariant(image))

This gives the error: AttributeError: type object 'QTextDocument' has no attribute 'ImageResource'

1

There are 1 best solutions below

2
On

I found a solution that works, and I think, either the QT6 documentation needs to be updated, or the PyQt6 implementation of the documentation needs to be developed. The required Integer is stored in the value attribute:

document.addResource(QtGui.QTextDocument.ResourceType.ImageResource.value, url, QtCore.QVariant(image))

QVariant method is not required, simpler code below:

document.addResource(QtGui.QTextDocument.ResourceType.ImageResource.value, url, image)