Multiple Viewports and resize in QOpenGLWidget

  • Hi there,
    I have a problem drawing multiple viewports on a QOpenGLWidget. Everything seems to work fine until i resize the window (after that the second viewport content disappears forever). Testbed: QT Examples --> Qt-5.4 --> Opengl --> cube
    changes to code:


    void MainWidget::resizeGL(int w, int h)
        this->w = w;
        this->h = h;
        // Calculate aspect ratio
        qreal aspect = qreal(w) / qreal(h ? h : 1);
        // Set near plane to 3.0, far plane to 7.0, field of view 45 degrees
        const qreal zNear = 3.0, zFar = 7.0, fov = 45.0;
        // Reset projection
        // Set perspective projection
        projection.perspective(fov, aspect, zNear, zFar);
        cam_projection.perspective(fov, 1.0f, zNear, zFar);
    //! [5]
    void MainWidget::paintGL()
        // Clear color and depth buffer
    //! [6]
        // Calculate model view transformation
        QMatrix4x4 matrix;
        matrix.translate(0.0, 0.0, -5.0);
        // Set modelview-projection matrix
        program.setUniformValue("mvp_matrix", projection * matrix);
    //! [6]
        // Use texture unit 0 which contains cube.png
        program.setUniformValue("texture", 0);
        // Draw cube geometry
        // Set modelview-projection matrix
        program.setUniformValue("mvp_matrix", cam_projection * matrix);

    add in h:

        // new
        int w,h;
        QMatrix4x4 cam_projection;

    Any Help appreciated,


  • Update:

    tried with qt 5.5, same behaviour.

  • Moderators

    QMatrix4x4::perspective multiplies the existing matrix by another. In the resetGL() method the original projection matrix is set to identity before perspective is applied, but you're not doing that for your cam_projection, so it gets cumulatively more and more distorted on every resize. Simply adding cam_projection.setToIdentity(); before applying perspective fixes the issue.

  • Thanks Chris. That solves the problem.

Log in to reply

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.