Search code examples
qtqpainter

In Qt drawPoint method does not plot anything if negative valued parameters are supplies


in Qt creator drawPoint() method does not put point if negative valued parameters are passed following is code for Bresenham's algorithm.but, it is not working in qt creator.it just plots circle in one quadrant.

Bresenham::Bresenham(QWidget*parent):QWidget(parent)  
{}

void  Bresenham::paintEvent(QPaintEvent *e)  
{  
     Q_UNUSED(e);  
     QPainter qp(this);  
     drawPixel(&qp);  
}  
void  Bresenham::drawPixel(QPainter *qp)  
{  
    QPen pen(Qt::red,2,Qt::SolidLine);  
    qp->setPen(pen);  
    int x=0,y,d,r=100;  
    y=r;  
    d=3-2*r;  
    do  
    {  
       qp->drawPoint(x,y);  
       qp->drawPoint(y,x);  
       qp->drawPoint(y,-x);  
       qp->drawPoint(x,-y);  
       qp->drawPoint(-x,-y);  
       qp->drawPoint(-y,-x);  
       qp->drawPoint(-x,y);  
       qp->drawPoint(-y,x);
       if(d<0)  
       {  
          d=d+4*x+6;  
       }  
       else  
       {  
          d=d+(4*x-4*y)+10;  
          y=y-1;  
       }  
       x=x+1;  
      }while(x<y); 
}

Solution

  • You need to translate the Qt coordinate system to the classic cartesian one. Choose a new center QPoint orig and replace all

    qp->drawPoint(x,y);  
    

    with

    qp->drawPoint(orig + QPoint(x,y));
    

    The Qt coordinates system origin is at (0,0) and the y-axis is inverted. For instance, a segment from A(2,7) to B(6,1) look like this:

    enter image description here

    Notice how there is only the positive-x, positive-y quadrant. For simplicity assume that no negative coordinates exist.

    Note:

    For performance reasons it is better to compute all the points first and then draw them all using

    QPainter::drawPoints ( const QPoint * points, int pointCount );