在画布上拖放一个点

时间:2014-02-17 20:03:00

标签: pyqt

如何在Canvas上的点上使用拖放技术?我没有在画布上找到任何插槽来连接鼠标点击。

class Canvas(QtGui.QWidget):
    def __init__(self, parent):
        super(Canvas, self).__init__(parent)
        self.setGeometry(0,0,200,200)

    def paintEvent(self, e):
        qp = QtGui.QPainter()
        qp.begin(self)
        self.drawPoints(qp)
        qp.end()

    def drawPoints(self, qp):
        qp.setPen(QtCore.Qt.red)
        size = self.size()

            #test
        x = 0
        y = 0
        for k in range(0,150,2):
            qp.drawPoint(x,y)
            x += 5
            y += 5

    #get the click coordinates
    def mousePressEvent(self, QMouseEvent):
        print QMouseEvent.pos()

1 个答案:

答案 0 :(得分:2)

拖拽技术或多或少是这样的:

  1. 点击:识别拖动对象
  2. 移动时:重绘拖动对象
  3. 发布时:更新最终状态
  4. 在第2步中,您还可以更新画布。这是该技术的一个例子。我使用numpy来管理积分(希望不要打扰你)。

    from PyQt4 import QtGui,QtCore
    import numpy as np
    
    class Canvas(QtGui.QWidget):
    
        DELTA = 10 #for the minimum distance        
    
        def __init__(self, parent):
            super(Canvas, self).__init__(parent)
            self.draggin_idx = -1        
            self.setGeometry(0,0,200,200)
            self.points = np.array([[v*5,v*5] for v in range(75)], dtype=np.float)        
    
        def paintEvent(self, e):
            qp = QtGui.QPainter()
            qp.begin(self)
            self.drawPoints(qp)
            qp.end()
    
        def drawPoints(self, qp):
            qp.setPen(QtCore.Qt.red)
            for x,y in self.points:
                qp.drawPoint(x,y)        
    
        def _get_point(self, evt):
            return np.array([evt.pos().x(),evt.pos().y()])
    
        #get the click coordinates
        def mousePressEvent(self, evt):
            if evt.button() == QtCore.Qt.LeftButton and self.draggin_idx == -1:
                point = self._get_point(evt)
                #dist will hold the square distance from the click to the points
                dist = self.points - point
                dist = dist[:,0]**2 + dist[:,1]**2
                dist[dist>self.DELTA] = np.inf #obviate the distances above DELTA
                if dist.min() < np.inf:
                    self.draggin_idx = dist.argmin()        
    
        def mouseMoveEvent(self, evt):
            if self.draggin_idx != -1:
                point = self._get_point(evt)
                self.points[self.draggin_idx] = point
                self.update()
    
        def mouseReleaseEvent(self, evt):
            if evt.button() == QtCore.Qt.LeftButton and self.draggin_idx != -1:
                point = self._get_point(evt)
                self.points[self.draggin_idx] = point
                self.draggin_idx = -1
                self.update()        
    
    app = QtGui.QApplication([])
    
    c = Canvas(None)
    c.show()
    app.exec_()