QGraphicsView - background grid - shifts/moves when pan/zooom...

  • Hey

    I've reimplemented scene drawBackground to generate a custom looking grid like :

        qreal left = int(rect.left()) - (int(rect.left()) % mGridSize);
        qreal top = int(rect.top()) - (int(rect.top()) % mGridSize);
        QVarLengthArray<QLineF, 100> lines;
        for (qreal x = left; x < rect.right(); x += mGridSize)
            lines.append(QLineF(x, rect.top(), x, rect.bottom()));
        for (qreal y = top; y < rect.bottom(); y += mGridSize)
            lines.append(QLineF(rect.left(), y, rect.right(), y));
        QVarLengthArray<QLineF, 100> thickLines;
        for (qreal x = left; x < rect.right(); x += mGridSize * 5)
            thickLines.append(QLineF(x, rect.top(), x, rect.bottom()));
        for (qreal y = top; y < rect.bottom(); y += mGridSize * 5)
            thickLines.append(QLineF(rect.left(), y, rect.right(), y));
        QPen myPen(Qt::NoPen);
        painter->setBrush(QBrush(QColor(55, 55, 55, 255)));
        QPen penHLines(QColor(75, 75, 75), 1, Qt::SolidLine, Qt::FlatCap, Qt::RoundJoin);
        painter->drawLines(lines.data(), lines.size());
        painter->setPen(QPen(QColor(100, 100, 100), 2, Qt::SolidLine, Qt::FlatCap, Qt::RoundJoin));
        painter->drawLines(thickLines.data(), thickLines.size());
        QVector<QPointF> points;
        for (qreal x = left; x < rect.right(); x += mGridSize) {
            for (qreal y = top; y < rect.bottom(); y += mGridSize) {
                points.append(QPointF(x, y));
        painter->drawPoints(points.data(), points.size());

    But when I place item close to gird lines/snap it and then move/zoom the view. The grid miss-aligns and changes its position...

    How can I correct it?


    EDIT I've move the function to view to capture pan/zoom events to see if I can somehow control the offset for the "thick lines" drawing...

    Here is the gif showing issue :

  • I've updated the question with gif/some updates... Still fighting with it o.o

    I think by using int vertOffset = horizontalScrollBar()->sliderPosition();
    I can somehow calculate the "jump" value offset and offset position of line by that. Not sure how yet tho...


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