QOpenGLShaderProgram example not working in QGraphicsItem



  • I am trying to use QOpenGLShaderProgram in a QGraphicsItem. I have a custom QGraphicsView where I have changed the viewport to a QGLWidget. My shader is getting compiled, linked and bound and is even drawing a triangle on the screen. But the color being passed to the fragment shader is being ignored. The triangle is always white. The shader example works if I use it in a QGLWidget, but not if it is part of a QGraphicsItem in a QGraphicsView. I am using Qt 5.2.

    Am I missing something in OpenGL? Or is this a bug?

    Here is some code: (though it is mostly copied from the example in the docs)

    @
    void MyGraphicsItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
    {
    if (mShaderProgram.bind())
    {
    static GLfloat const triangleVertices[] = {
    10.0f, 110.0f, 0.0f,
    110.0f, 110.0f, 0.0f,
    60.0f, 10.0f, 0.0f
    };

        QColor color(0, 255, 0, 255);
    
        QMatrix4x4 pmvMatrix;
    
        painter->beginNativePainting();
    
            pmvMatrix.ortho(mBoundingRect);
    
            mShaderProgram.enableAttributeArray("vertex");
            mShaderProgram.setAttributeArray("vertex", triangleVertices, 3);
            mShaderProgram.setUniformValue("matrix", pmvMatrix);
            mShaderProgram.setUniformValue("color", color);
    
            glDrawArrays(GL_TRIANGLES, 0, 3);
    
            mShaderProgram.disableAttributeArray("vertex");
    
        painter->beginNativePainting();
    
        mShaderProgram.release();
    }
    

    }
    @

    @
    void MyGraphicsItem::InitializeShaders()
    {
    if (!mShaderProgram.addShaderFromSourceCode(QOpenGLShader::Vertex,
    "attribute highp vec4 vertex;\n"
    "uniform highp mat4 matrix;\n"
    "void main(void)\n"
    "{\n"
    " gl_Position = matrix * vertex;\n"
    "}"))
    {
    qDebug() << "could not add vertex shader";
    }

    if (!mShaderProgram.addShaderFromSourceCode(QOpenGLShader::Fragment,
        "uniform mediump vec4 color;\n"
        "void main(void)\n"
        "{\n"
        "   gl_FragColor = color;\n"
        "}"))
    {
        qDebug() << "could not add fragment shader";
    }
    
    if (!mShaderProgram.link())
    {
        qDebug() << "could not link shader program";
    }
    if (!mShaderProgram.bind())
    {
        qDebug() << "could not bind shader program";
    }
    

    }
    @


Log in to reply
 

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