How to set QImage pixel colour for an RGB888 image in Qt

Bill Cheatham picture Bill Cheatham · Dec 19, 2011 · Viewed 31.3k times · Source

I have an RGB888 format qImage defined as follows:

myQrgb = QImage(img_in, width, height, QImage::Format_RGB888);

I wish to alter specific pixel values, so I followed the example here, like so:

QRgb value = qRgb(0, 0, 0);
myQrgb.setPixel(i, j, value);

This, however, always produces a segmentation fault regardless of the values of i and j (e.g. i = j = 2).

I am guessing it is because I am incorrectly using QRgb to manipulate pixels in a QImage::Format_RGB888. What should I do instead?

Answer

Dave Mateer picture Dave Mateer · Dec 19, 2011

I think the problem may be more related to the img_in data with which you are initializing the image. Are you sure that data is valid?

The following example successfully paints a white square with a black square in the corner.

#include <QtGui>

int main(int argc, char **argv) {
  QApplication app(argc, argv);

  QImage img(100, 100, QImage::Format_RGB888);
  img.fill(QColor(Qt::white).rgb());

  for (int x = 0; x < 10; ++x) {
    for (int y = 0; y < 10; ++y) {
      img.setPixel(x, y, qRgb(0, 0, 0));
    }
  }

  QLabel l;
  l.setPixmap(QPixmap::fromImage(img));
  l.show();

  return app.exec();
}