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

I am 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, if I don't enable anti-aliasing, moving objects around will sometimes leave artifacts in the mesh (in areas where it was not drawn). This seems to happen mostly at low zoom levels, where the view is zoomed out a bit. Any ideas what I might be doing wrong here?

I would not want to turn anti-aliasing because the lines are strictly horizontal and vertical, and I would like them to be as clear as possible.

Any help is very helpful, Regards, Elvis

+2


a source to share


1 answer


It looks like you need to use a different method to update the viewport:

http://doc.qt.io/qt-5/qgraphicsview.html#viewportUpdateMode-prop



and possibly background caching:

http://doc.qt.io/qt-5/qgraphicsview.html#cacheMode-prop

+2


a source







All Articles