开发者

paintEvent() in PyQt called unnecessarily

I'm using PyQt4 and I want to draw a line based on user's click on an existing image which is displayed as an imagelabel. The image sh开发者_JAVA百科ows properly and after a clicking an icon in toolbar, the user will draw a line on the image.

I've overridden the mousePressEvent() and mouseReleaseEvent() to get the x, y positions. I've defined paintEvent() to draw the line.

def mousePressEvent(self,event):
    self.startx=event.x()
    self.starty=event.y()

def mouseReleaseEvent(self,event):
    self.endx=event.x()
    self.endy=event.y()

def paintEvent(self,event):
    painter=QPainter()
    painter.begin(self)
    painter.setPen(QPen(Qt.darkGray,3))
    painter.drawLine(self.startx,self.starty,self.endx,self.endy)
    painter.end()

Problem:

  1. Since I used self for mouseevents, the error says: object has no attribute 'self.startx' — (How should I associate a widget to mouseevents in PyQt?)
  2. paintEvent() gets called even when i move the mouse around the app.

Thanks in advance…


I would recommend making the line a seperate object that gets created once you release the mouse. To do so create a new class:

class line(QtGui.QWidget):
    def __init__(self, point1, point2):
        self.p1 = point1
        self.p2 = point2

    def paintEvent(self,event):
        painter=QPainter()
        painter.begin(self)
        painter.setPen(QPen(Qt.darkGray,3))
        painter.drawLine(self.p1,self.p2)
        painter.end()

Then I would define your mouse events like follows.

def mousePressEvent(self,event):
    self.startx=event.x()
    self.starty=event.y()
def mouseReleaseEvent(self,event):
    self.endx=event.x()
    self.endy=event.y()
    newLine = line(QtCore.QPoint(self.startx, self.starty), QtCore.QPoint(self.endx, self.endy))

This should allow the user to click and drag the mouse and then upon releasing the mouse it should draw the line and not effect whatever else is drawn. I usually do things in QGraphicsScenes and it is a little bit different, but the concept should be about the same for this. If you want to have the line being drawn as the user drags the mouse I know how to do that also, but the way I know is much more complicated than this and I would recommend using a QGraphicsScene to handle that, just message me if you want me to explain how I have done it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜