在QImage上绘制矩形而不显示它

时间:2020-07-29 16:48:33

标签: python python-3.x pyqt pyqt5 qimage

我想在QImage上方绘制矩形并将结果另存为png。下面的最小示例应执行此操作。

from PyQt5.QtGui import QImage, QColor, QPainter, QBrush
from PyQt5.QtWidgets import QApplication, QMainWindow, QWidget

import sys

class Window(QMainWindow):

    def __init__(self):
        super().__init__()
        self.title = "PyQt5 Drawing Tutorial"
        self.top = 150
        self.left = 150
        self.width = 500
        self.height = 500
        self.mypainter = MyPainter()
        self.mypainter.create()
        self.InitWindow()
    def InitWindow(self):
        self.setWindowTitle(self.title)
        self.setGeometry(self.top, self.left, self.width, self.height)
        self.show()

class MyPainter(QWidget):
    def __init__(self):
        super().__init__()
        self.img = QImage(25, 25, QImage.Format_RGBA64)
        self.color1 = QColor(255, 0, 0, 255)
        self.color2 = QColor(0, 255, 0, 255)
        self.color3 = QColor(0, 0, 255, 255)
        self.boxes = (
            (2, 2, 10, 10),
            (5, 5, 4, 5),
            (10, 10, 10, 7))

    def create(self):
        self.colors = (
            self.color1,
            self.color2,
            self.color3)
        for idx,  box in enumerate(self.boxes):
            self.color = self.colors[idx]
            self.bndboxSize = box
            self.repaint()
        self.img.save("myImg.png")

    def paintEvent(self, event):
        painter = QPainter(self)
        painter.drawImage(self.rect(), self.img)
        painter.setBrush(QBrush(self.color))
        painter.drawRect(self.bndboxSize)

App = QApplication(sys.argv)
window = Window()
sys.exit(App.exec())

我所期望的

enter image description here

黑色背景也可以是透明的。

我得到了什么

enter image description here

这只是带有alpha通道的图像,如果将鼠标悬停,您将获得链接

我得到了什么(调试模式)

enter image description here

我不知道如何获得想要的图像。

1 个答案:

答案 0 :(得分:2)

如果要创建图像,则不必使用小部件,但必须使用QPainter在QImage上绘画。在OP的尝试中,将其绘制在QWidget上,并且QImage仅具有噪点。

from PyQt5.QtCore import QRect, Qt
from PyQt5.QtGui import QColor, QGuiApplication, QImage, QPainter


def create_image():
    img = QImage(25, 25, QImage.Format_RGBA64)
    img.fill(Qt.black)

    painter = QPainter(img)

    colors = (QColor(255, 0, 0, 255), QColor(0, 255, 0, 255), QColor(0, 0, 255, 255))
    boxes = (QRect(2, 2, 10, 10), QRect(5, 5, 4, 5), QRect(10, 10, 10, 7))

    for color, box in zip(colors, boxes):
        painter.fillRect(box, color)

    painter.end()

    return img


def main():
    app = QGuiApplication([])
    qimage = create_image()
    qimage.save("myImg.png")


if __name__ == "__main__":
    main()

输出:

enter image description here

相关问题