Artifacts when trying to draw background grid without anti-aliasing in a QGraphicsScene

Posted by estan on Stack Overflow See other posts from Stack Overflow or by estan
Published on 2010-05-06T07:05:43Z Indexed on 2010/05/06 7:08 UTC
Read the original article Hit count: 239

Filed under:
|

Hi folks,

I'm trying to draw a background grid in the drawBackground() function of my QGraphicsScene subclass:

void Scene::drawBackground(QPainter *painter, const QRectF &rect)
{
    const int gridSize = 50;

    const int realLeft = static_cast<int>(std::floor(rect.left()));
    const int realRight = static_cast<int>(std::ceil(rect.right()));
    const int realTop = static_cast<int>(std::floor(rect.top()));
    const int realBottom = static_cast<int>(std::ceil(rect.bottom()));

    // Draw grid.
    const int firstLeftGridLine = realLeft - (realLeft % gridSize);
    const int firstTopGridLine = realTop - (realTop % gridSize);

    QVarLengthArray<QLine, 100> lines;

    for (qreal x = firstLeftGridLine; x <= realRight; x += gridSize)
        lines.append(QLine(x, realTop, x, realBottom));
    for (qreal y = firstTopGridLine; y <= realBottom; y += gridSize)
        lines.append(QLine(realLeft, y, realRight, y));

    //painter->setRenderHint(QPainter::Antialiasing);
    painter->setPen(QPen(QColor(220, 220, 220), 0.0));
    painter->drawLines(lines.data(), lines.size());

    // Draw axes.
    painter->setPen(QPen(Qt::lightGray, 0.0));
    painter->drawLine(0, realTop, 0, realBottom);
    painter->drawLine(realLeft, 0, realRight, 0);
}

However, unless I turn on anti-aliasing, moving items around will sometimes leave artifacts in the grid (areas where it's not drawn). It seems it mostly happens at low zoom levels, when the view is zoomed out a bit. Any ideas what I might be doing wrong here?

I'd really don't want to turn anti-aliasing on since the lines are strictly horizontal and vertical, and I'd like them to be as crisp as possible.

Any help is much appriciated, Regards, Elvis

© Stack Overflow or respective owner

Related posts about c++

Related posts about qt