简体   繁体   中英

How draw a putpixel in python?

I want to draw a pixel, this is my function, i want create a function to put a pixel

class Pixel(QPainter):
    def putPixel(self, x,y, value):
        self.begin(self)
        self.drawPoint(QPoint(x, y))
        self.end()

i am using, that function

        qp = QPainter()
        pixel = Pixel(qp)
        pixel.putPixel(100, 100,1)

what is the problem? i am getting this error:

TypeError: arguments did not match any overloaded call:
  QPainter(): too many arguments
  QPainter(QPaintDevice): argument 1 has unexpected type 'QPainter'

QPainter is a painter class, that is, it has the task of painting some QPaintDevice such as QPixmap, QImage, QWidget, etc. But in your code when using "self.begin(self)" you are indicating that the QPainter is going to paint itself and that has no logic. On the other hand you don't use value at all which is also inconsistent.

The correct logic is that before calling putPixel the device must be set:

from PyQt5.QtCore import QPoint
from PyQt5.QtGui import QColor, QPainter, QPen
from PyQt5.QtWidgets import QApplication, QWidget


class PixelPainter(QPainter):
    def putPixel(self, x, y, value):
        self.save()
        pen = QPen(QColor(value))
        pen.setWidth(1)
        self.setPen(pen)
        self.drawPoint(QPoint(x, y))
        self.restore()


class Widget(QWidget):
    def paintEvent(self, event):
        painter = PixelPainter()
        painter.begin(self)
        for x in range(200):
            painter.putPixel(x, x, QColor("red"))
        painter.end()


if __name__ == "__main__":
    import sys

    app = QApplication(sys.argv)
    w = Widget()
    w.resize(640, 480)
    w.show()
    sys.exit(app.exec_())

you can modify this part

def putPixel(self,x,y, value):
        self.save()
        self.drawPoint(QPoint(x, y))
        self.restore()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM