pythonpython-3.xpyqt5qpixmapqdockwidget

How to add an image in pyqt qdock widget


I am trying to create a image viewer using pyqt. What i am trying is to create a qdockwidget to display the image. I have created the qPixmap objecte and tried to add it as a widget in qdockwidget.

from PyQt5 import QtWidgets, QtGui
from PyQt5.QtWidgets import (QApplication, QMainWindow)
from PyQt5.QtCore import Qt

from reportlab.graphics.charts.piecharts import Pie
from reportlab.graphics.shapes import *

from PIL import ImageQt

from reportlab.graphics import renderPM

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.resize(800, 600)

        dockWidget = QtWidgets.QDockWidget()
        dockWidget.setWindowTitle("Image Viewer")

        d = Drawing(200, 100)
        pc = Pie()
        pc.x = 65
        pc.y = 0
        pc.width = 100
        pc.height = 100
        pc.data = [10, 20, 30, 40, 50, 60]
        pc.labels = ['a', 'b', 'c', 'd', 'e', 'f']
        pc.slices.strokeWidth = 0.5
        pc.slices[3].popout = 10
        pc.slices[3].strokeWidth = 2
        pc.slices[3].strokeDashArray = [2, 2]
        pc.slices[3].labelRadius = 1.75
        pc.slices[3].fontColor = colors.red
        d.add(pc)

        test = renderPM.drawToPILP(d)

        QtImage1 = ImageQt.ImageQt(test)
        QtImage2 = QtGui.QImage(QtImage1)
        pixmap = QtGui.QPixmap.fromImage(QtImage2)
        label = QtWidgets.QLabel('testing', self)
        label.setPixmap(pixmap)

        #dockWidget.setWidget(pixmap)
        dockWidget.setFloating(False)
        self.addDockWidget(Qt.RightDockWidgetArea, dockWidget)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    myWidget = MainWindow()
    myWidget.show()

    sys.exit(app.exec_())

Solution

  • A QPixmap is not a visual element but an object that has the image information optimized to be rendered in the widgets, so it cannot be added to the QDockWidget directly, but you must use a widget that allows it to be shown, such as the QLabel:

    dockWidget.setWidget(label)