PDA

View Full Version : Drawing Lines In Real Time (PyQt)



n3ziy
23rd April 2016, 19:48
I'm making an application and I want to connect certain items in the QGraphicsScene by using lines. I want this done in real time, so while I'm holding the mouse down and trying to draw the line I want to see the line being drawn. I've written some code to allow this but the problem with this code is that it keeps on clearing everything and I dont know a way around this. Any help would be much appreciated.

class graphicsScene(QtGui.QGraphicsScene, QtGui.QWidget):
self.pen = QtGui.QPen(QtCore.Qt.black, 3, QtCore.Qt.SolidLine)


def mousePressEvent(self, event):
if connectLine_cs == 1:
self.cursorStartPosition = event.scenePos()
self.start = QtCore.QPoint(self.cursorStartPosition.x(),self.cu rsorStartPosition.y())

def mouseMoveEvent(self, event):
if connectLine_cs == 1:
self.cursorCurrentPosition = event.scenePos()
current = QtCore.QPointF(self.cursorCurrentPosition.x(),self .cursorCurrentPosition.y())
self.clear()
link = QtGui.QGraphicsLineItem(QtCore.QLineF(self.start, current))
link.setPen(self.pen)
self.addItem(link)

d_stranz
24th April 2016, 19:09
You realize that your call to self.clear() is of course deleting all of the items from your scene every time you move the mouse, right?

One way to do what you want is to use QRubberBand. The other is to start and add a new line item to the scene on mouse down (and remember it), update that same line's endpoint on mouse move, and then stop updating on mouse up.

Please use [CODE] tags when posting code to make it more readable. Click "Go advanced" then click the "#" icon to insert a pair of tags, and put your code between them. This is especially important for Python where formatting and indentation make all the difference.