void MainWindow::paintEvent(QPaintEvent *e) { QPainter painter(this); painter.setBrush(QBrush(Qt::red,Qt::SolidPattern)); painter.drawRect(10,10,100,100); } 

With this code, how do you know the color of a pixel (20,20)?

I found this method on the Internet, but it does not work

 QPixmap qPix = QPixmap::grabWidget(ui->centralWidget); QImage image(qPix.toImage()); QColor color(image.pixel(20, 20)); 

    1 answer 1

    Something like that:

     QColor QMainWindow::getPixelAt(int x, int y) { return grab(QRect(x, y, 1, 1)).toImage().pixelColor(0,0); } 

    But this code cannot be called directly from MainWindow :: paintEvent (QPaintEvent * e), since the use of the grab method causes a call to this paintEvent itself, and infinite recursion will occur. So it turns out nonsense. If you need to know the state of the target pixel at the time of drawing, IMHO it is better to have an intermediate buffer and work with it, and then draw its final state on the widget.