I have an RGB888 format qImage defined as follows:
int sizeX = 300; int sizeY = 300;
QImage img = QImage(sizeX, sizeY, QImage::Format_RGB888);
I wish to print current pixel of img one by one. So, I followed the example here:`
for(int i=0; i<sizeX; i++){
for(int j=0; j<sizeY; j++){
img.setPixel(i, j, qRgb(rand()%256, rand()%256, rand()%256));
}
}
QGraphicsScene *graphic = new QGraphicsScene(this);
graphic->addPixmap(QPixmap::fromImage(img));
ui->graphicsView->setScene(graphic);
But it prints the whole QImage. I want to print one by one. Thanks. Best regards.
As JarMan commented, you are looking for "animation".
Drawing pixel by pixel, and updating the UI for every pixel, may use animation solution as described in the following post.
In Qt5 we have to execute QtWidgets.QApplication.processEvents()
for forcing Qt to redraw.
Note:
I implemented the code in Python (with PyQt5), the syntax is different from C++, but the concept is the same.
Initialization stage:
QGraphicsView
class.graphic = QGraphicsScene(0, 0, sizeX, sizeY)
pixmap = QPixmap.fromImage(img)
graphic
object, and keep the returned reference:pixmap_item = graphic.addPixmap(pixmap)
setScene(graphic)
Animation:
In the animation loop, we have to execute setPixmap
on every iteration for updating the entire image.
(The is a way for drawing pixel by pixel, but it's a deviation from your question).
Simplified code for updating the image (executed each iteration):
img.setPixel(i, j, qRgb(randrange(256), randrange(256), randrange(256)));
pixmap = QPixmap.fromImage(img)
pixmap_item.setPixmap(pixmap)
QtWidgets.QApplication.processEvents()
Complete Python code sample:
import sys
from PyQt5.QtWidgets import QGraphicsScene, QGraphicsView, QApplication
from PyQt5 import QtWidgets
from PyQt5.QtGui import QImage, QPixmap, QPainter, QColor, qRgb
from random import randrange
import time
class Example(QGraphicsView):
def __init__(self):
super().__init__()
self.mPixmap = QPixmap()
self.sizeX = 300
self.sizeY = 300
self.img = QImage(self.sizeX, self.sizeY, QImage.Format_RGB888)
self.img.fill(QColor(60, 60, 60)) # Fill image with gray color
self.initUI()
def initUI(self):
self.graphic = QGraphicsScene(0, 0, self.sizeX, self.sizeY)
self.pixmap = QPixmap.fromImage(self.img)
self.pixmap_item = self.graphic.addPixmap(self.pixmap)
self.setScene(self.graphic)
self.show()
def doAnimation(self):
for i in range(self.sizeX):
for j in range(self.sizeY):
self.img.setPixel(i, j, qRgb(randrange(256), randrange(256), randrange(256)));
pixmap = QPixmap.fromImage(self.img)
self.pixmap_item.setPixmap(pixmap)
QtWidgets.QApplication.processEvents()
time.sleep(0.001) # Sleep 1msec (In Python it's slow enough without the sleep...)
if __name__ == '__main__':
app = QApplication(sys.argv)
example = Example()
example.doAnimation()
app.exec_()
I hope it's not too much Python for you...