Search code examples
c++qtopenglclipping

Text Clipping with Qt OpenGL


I'm currently working with Qt5.1 and trying to draw some OpenGL stuff within a QGLWidget:

void Widget::paintGL() {
    startClipping(10, height()-110,100,100);

    qglColor(Qt::red);
    glBegin(GL_QUADS);
        glVertex2d(0,0);
        glVertex2d(500,0);
        glVertex2d(500,500);
        glVertex2d(0,500);
    glEnd();

    qglColor(Qt::green);
    this->renderText(50, 50, "SCISSOR TEST STRING");

    endClipping();
}

The quad gets clipped correctly but the text doesn't. I tried three ways of implementing the startClipping method: scissor test, setting the viewport to the clipping area and with a stencil buffer. None of them worked and the whole string was drawn instead of beeing cut off at the edges of the clipping area.

Now my question is: Is this behavior a bug of Qt or is there something, I missed or another possibility I could try??


Solution

  • After a week of trying around, I suddenly found a very simple way to achieve, what I was looking for. Using a QPainter and it's methods instead of the QGLWidget's renderText() simply makes text clipping work:

    QPainter *painter = new QPainter();
    painter->begin();
    
    painter->setClipping(true);
    
    painter->setClipPath(...);   // or
    painter->setClipRect(...);   // or
    painter->setClipRegion(...);
    
    painter->drawText(...);
    
    painter->end();