Question: I want to visualize a matrix of integer values between 0 and 255 as a gray-scale image in Qt 5.12. First, I built a sample 256x256 uchar array with values between 0 and 255 in each row. then I tried to show the image with QImage and format\_grayscale as the format. But confusingly, the resulting image contains disturbed pixels in the last rows.

The Resulting Image

![](https://i.stack.imgur.com/tzYpc.png)

I also created a gray-scale color map and tried with format\_indexed8, but the same result. Here is my code.

```
uchar imageArray[256][256];
for (int i = 0; i < 256; i++)
{
    for (int j = 0; j < 256; j++)
    {
        imageArray[i][j] = uchar(j);
    }
}

QImage image(&imageArray[0][0],
                256,
                256,
                QImage::Format_Grayscale8);

```

Answer: 
My guess is your buffer is deallocated and partially overwritten before you can get it displayed. It is your responsability to ensure the data buffer remains valid when using a constructor that does not perform a deep copy.

Quoting from [the Qt documentation](https://doc.qt.io/qt-5/qimage.html#QImage-3):

> 
> Constructs an image with the given width, height and format, that uses
>  an existing memory buffer, data. The width and height must be
>  specified in pixels. bytesPerLine specifies the number of bytes per
>  line (stride).
> 
> 
> The buffer must remain valid throughout the life of the QImage and all
>  copies that have not been modified or otherwise detached from the
>  original buffer. The image does not delete the buffer at destruction.
>  You can provide a function pointer cleanupFunction along with an extra
>  pointer cleanupInfo that will be called when the last copy is
>  destroyed.
> 
> 
>
You should not use a matrix but an array of size 256x256 = 65535 ,  

So instead of : 

```
uchar imageArray[256][256]; 

```

use : 

```
uchar imageArray[65536];

```

Then fill your array with the values you want.
Then, call the constructor of QImage : 

```
QImage image(imageArray, 256, 256, QImage::Format_Grayscale8);

```