Search code examples
c++qtopenglqglwidget

Line get duplicated instead of moved


I'm using qWidget which inherits QGLWidget and below the widget I have 2 buttons. button1: + button2: -

this is my code:

void GLWidget::paintGL() {

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glOrtho(0,_w,0,_h,-1,1);
    glViewport(_camera_pos_x,0,_w,_h);

    glBegin(GL_LINES);
        glVertex2i(50,50);
        glVertex2i(200,200);
    glEnd();

   update();
}

I want each time I'm pressing the + button, the screen will move 10 pixels to the right which means the line should move to the left by 10 pixels.

This is the code when im pressing the button:

void right() {_camera_pos_x += 10;}

_camera_pos_X is just a member int which is initialized to 0.

When I'm pressing the button another line is rendered 10 pixels to the right and I see 2 lines

What's wrong with my code?

By the way, I think im using old code of OpenGL, is there a better way to render a line?


Solution

  • First of all note, that drawing with glBegin/glEnd sequences is deprecated since more than 10 years. Read about Fixed Function Pipeline and see Vertex Specification for a state of the art way of rendering.


    glViewport specifies the transformation from normalized device coordinates to window coordinates. If you want to change the position of the line, then you have to draw the line at a different position, but that doesn't change the size of the viewport. Keep your viewport as large as the window:

    glViewport(0, 0, _w, _h);
    

    The default frame buffer is never cleared, so the rendering is always drawn on the rendering of the previous frames. Because of that, you can "see 2 lines". Use glClear to clear the framebuffer at the begine of the rendering:

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    

    Change the model view matrix to set the positon of the line:

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glOrtho(0,_w,0,_h,-1,1);
    glViewport(0, 0, _w, _h);
    
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    glTranslatef(_camera_pos_x, 0.0f, 0.0f);
    
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    
    glBegin(GL_LINES);
        glVertex2i(50,50);
        glVertex2i(200,200);
    glEnd();