在QImage中鼠标按下的位置设置一个十字



我在QImage中显示了一个图形,并希望设置一个黄色的十字(+)用于测量,如果按下鼠标右键。

        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 
         }
        }

如果我在painteevent(…)中这样做,就会破坏原始图片。我该怎么做呢?

附加信息:对图像进行索引。

 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有一个黑色背景,我想画一个白色的十字——>(这是索引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);
      }

从你的评论来看,你不能用Format_Indexed8在QImage上画画。

从QImage文档:

警告:不支持在QImage::Format_Indexed8格式的QImage上绘制。

选择不同的格式,如QImage:: format_argb32_premultiply,事情应该工作。

另一种快速而不干净的方法是简单地在图像数据中设置值。

您将不得不做更多的工作-因为没有行命令,请参阅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);
}

最新更新