Drawing a square (problem with coordinates)

Hi,
I’m having a problem drawing a square in my (to be) application. In some quadrants drawing works, but usually it doesn’t. I think the problem is with the coordinates (the y one, I guess), because when I click, the square is created several pixels apart (10 at least).
If needed, I can attach or send link to a video, showing the problem.
Here’s the code which is supposed to draw the square :

void MainWindow::mousePressEvent(QMouseEvent *event)
    {
        event->pos();
        QString mousePosition;
        mousePosition="X: " + QString::number(event->x()) + " ";
        mousePosition+="Y: " + QString::number(event->y());
       statusBar()->showMessage(mousePosition);
        toGLCoords(event->x(),event->y(),mouseX,mouseY);
        mousePosition+=" X: " + QString::number(mouseX) + " Y: " + QString::number(mouseY);
        statusBar()->showMessage(mousePosition); 
        Square * kv4 = new Square (mouseX,mouseY,mouseX,mouseY);
        spisyk.push_back(kv4);
        w->paintGL();
   }

 void MainWindow::mouseMoveEvent(QMouseEvent *event)
    {   toGLCoords(event->x(),event->y(),mouseX,mouseY);
        Obekt *kv5=spisyk.back();
        spisyk.pop_back();
        kv5->setP2(mouseX,mouseY);
        spisyk.push_back(kv5);
        w->paintGL();
        QString mousePosition;
        mousePosition="X: " + QString::number(event->x()) + " ";
        mousePosition+="Y: " + QString::number(event->y());
        mousePosition+=" X: " + QString::number(mouseX) + " Y: " + QString::number(mouseY);
        statusBar()->showMessage(mousePosition); 
}

 void MainWindow::toGLCoords(double X,double Y,double &x,double &y)
    {
        GLint viewport[4];
        glGetIntegerv(GL_VIEWPORT, viewport);
        GLdouble modelview[16];
        glGetDoublev(GL_MODELVIEW_MATRIX, modelview);
        GLdouble projection[16];
        glGetDoublev(GL_PROJECTION_MATRIX, projection);
        GLdouble Z;
        gluUnProject( X, Y, 0, modelview, projection, viewport, &x, &y, &Z);
        cout << "X: " << x << endl << "Y: " << y << endl;
 }

And the last function is the draw() one :

void  Square::draw()
{
 glRectf(p1[0],p1[1],p2[0],p2[1]);
   glPopMatrix();
    glFlush();
}

Thanks for the help in advance! :slight_smile:

That ‘10 pixel’ offset can be a result of using wrong mouse coordinates. If your event uses window coordinates then you have to convert them to client coordinates before passing them to gluUnProject.
In fullscreen applications client area is equal to window area (no border and title bar), but in regular windowed applications you have to take differences between window and client coordinates into account.

Thank you very much! I substracted the toolbar coords and now it works :slight_smile: