Set a cross in QImage at the position, where mousepressed

2.3k views Asked by At

I have a graph shown in a QImage and want to set a cross (+) in yellow colour for measurement, if right mouse button is pressed.

        void foo::mousePressEvent(QMouseEvent *event)
        {
         if (event->button() == Qt::RightButton) {
            QPoint pos = event->pos();
            int x = pos.x();
           int y = pos.y();
          QLine line(x-5,y,x+5,y);
          QLine line(x,y-5,x,y+5);
          QPainter painter(&my_image);
          painter.setPen( Qt::red );
          painter.setBrush( Qt::yellow );
/*
QPainter::begin: Cannot paint on an image with the QImage::Format_Indexed8 format
QPainter::setPen: Painter not active
QPainter::setBrush: Painter not active
*/


              painter.drawLine(line); //no effect 

         }
        }

if I do it in Paintevent(...), I destroy the original pic. how can I do it.

additional Information: the imag is indexed.

 my_image.setColorCount(33);
    for(int i = 0;i<33;i++)
    {
        my_image.setColor(i,qRgb((unsigned char)palette[i*3], (unsigned char)palette[i*3+1], (unsigned char)palette[i*3+2]));
    }

my_imag has a black-Background and I want to draw a cross in white color --> (this is the index 32)

int color = 32;//_index_value_of_cross_color;

      for (int ix=x-5;ix<x+5;ix++) {
           my_image.setPixel(ix,y,color);
      }

      for (int iy=y-5;iy<y+5;iy++) {
           my_imag.setPixel(x,iy,color);
      }

but I see no effect !

2

There are 2 answers

2
Martin Beckett On

Another quick and dirty alternative is to simply set the values in the image data.

You will have to do a little more work - because there is no line command, see setpixel

int x = pos.x();
int y = pos.y();
int color = _index_value_of_cross_color;

for (int ix=x-5;ix<x+5;ix++) {
     my_image.setPixel(ix,y,color);
}

for (int iy=y-5;iy<y+5;iy++) {
     my_image.setPixel(x,iy,color);
}
2
Trenton Schulz On

From your comments, you cannot paint on a QImage with Format_Indexed8.

From the QImage docs:

Warning: Painting on a QImage with the format QImage::Format_Indexed8 is not supported.

Choose a different format like QImage::Format_ARGB32_Premultiplied and things should work.