PDA

View Full Version : [Solved] What's wrong with my grid drawing code?

enjoysmath
10th August 2015, 00:55
Here's the paint 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)

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

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

Added after 8 minutes:

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)