Help me please. What is wrong doing?
Created a paintwidget class from QWidget (the project itself). I want to make a simple fill solid area (like floodFill in Delphi).
Implemented drawing:
void PaintWidget::paintEvent(QPaintEvent *event) { QPainter pnt(this); QRect dirtyRect = event->rect(); pnt.drawImage(dirtyRect, image, dirtyRect); } void PaintWidget::mousePressEvent(QMouseEvent *event) { if ( event->button() == Qt::LeftButton ) { MP1=event->pos(); isDrawing = true; if (ActiveTool == 7) // если активный инструмент заливка { QColor oldClr, newClr; oldClr = image.pixel(MP1); newClr = myBrush.color(); //Fill(oldClr, newClr, MP2); Fill2(oldClr.rgb(), newClr.rgb(), MP1.x(), MP1.y()); update(); } } event->accept(); }
Here is the filling (I took the first filling from here , the second from cyberforum)
void PaintWidget::Fill(QColor oldClr, QColor newClr, QPoint p) { QPainter pnt(&image); pnt.setPen(QPen(newClr)); if( image.pixel(p) == oldClr.rgb() && image.pixel(p) != newClr.rgb() ) { pnt.drawPoint(p); Fill(oldClr,newClr,QPoint(px()+1,py())); Fill(oldClr,newClr,QPoint(px(),py()+1)); Fill(oldClr,newClr,QPoint(px()-1,py())); Fill(oldClr,newClr,QPoint(px(),py()-1)); } update(); } void PaintWidget::Fill2(QRgb oldColor, QRgb newColor, int x, int y) { if (oldColor == newColor) return; QStack<QPoint> stk; QPoint pt; int y1; bool spanLeft, spanRight; stk.push(QPoint(x, y)); while( !stk.empty() ) { pt = stk.pop(); x = pt.x(); y = pt.y(); y1 = y; while (y1 >= 0 && image.pixel(x, y1) == oldColor) y1--; y1++; spanLeft = spanRight = false; while (y1 < image.height() && image.pixel(x, y1) == oldColor) { image.setPixel(x, y1, newColor); if (!spanLeft && x > 0 && image.pixel(x-1, y1) == oldColor) { stk.push(QPoint(x-1, y1)); spanLeft = true; } else if(spanLeft && x > 0 && image.pixel(x-1, y1) != oldColor) { spanLeft = false; } if (!spanRight && x < (image.width() - 1) && image.pixel(x+1, y1) == oldColor) { stk.push(QPoint(x+1, y1)); spanRight = true; } else if(spanRight && (x < image.width() - 1) && image.pixel(x+1, y1) != oldColor) { spanRight = false; } y1++; } } }