# Thread: [Solved] What's wrong with my grid drawing code?

1. Beginner
Join Date
Apr 2015
Posts
11
Qt products
Platforms

## [Solved] What's wrong with my grid drawing code?

Here's the paint code:
Qt Code:
`def paint(self, painter, option, widget):            painter.setRenderHint(QPainter.Antialiasing)            pen = self.pen            painter.setPen(pen)            box = self.boundingRect()             #Calculate first horizontal line at the top            diffY = box.y() - self.anchorPoint.y()            y = self.yDist - (diffY - math.floor(diffY / self.yDist)) + box.y()             yNum = math.floor((box.height() - y) / self.yDist) + 1             #Calculate first vertical line on left            diffX = box.x() - self.anchorPoint.x()            x = self.xDist - (diffX - math.floor(diffX / self.xDist)) + box.x()            xNum = math.floor((box.width() - x) / self.xDist) + 1                     for i in range(0, yNum):                y2 = y + i * self.yDist                line = QLineF(box.x(), y2, box.x() + box.width(), y2)                painter.drawLine(line)             for i in range(0, xNum):                x2 = x + i * self.xDist                line = QLineF(x2, box.y(), x2, box.y() + box.height())                painter.drawLine(line)`
To copy to clipboard, switch view to plain text mode

boundingRect() returns the viewable scene area using the viewport() trick

Some lines are drawn all the way across and some aren't.

Fixed it. Here's the code:

def paint(self, painter, option, widget):
painter.setRenderHint(QPainter.Antialiasing)
pen = self.pen
painter.setPen(pen)
box = self.boundingRect()

#Calculate first horizontal line at the top
diffY = box.y() - self.anchorPoint.y()
y = self.anchorPoint.y() + math.floor(diffY / self.yDist)*self.yDist
yNum = math.floor((box.y() + box.height() - y) / self.yDist) + 1

#Calculate first vertical line on left
diffX = box.x() - self.anchorPoint.x()
x = self.anchorPoint.x() + math.floor(diffX / self.xDist)*self.xDist
xNum = math.floor((box.x() + box.width() - x) / self.xDist) + 1

for i in range(0, yNum):
y2 = y + i * self.yDist
line = QLineF(box.x(), y2, box.x() + box.width(), y2)
painter.drawLine(line)

for i in range(0, xNum):
x2 = x + i * self.xDist
line = QLineF(x2, box.y(), x2, box.y() + box.height())
painter.drawLine(line)
Last edited by enjoysmath; 9th August 2015 at 23:55.