如何鼠标拖动缩放固定到鼠标拖动起始位置的QGraphicsView?

时间:2017-03-08 21:17:00

标签: qt pyqt mouseevent zoom qgraphicsview

我试图点击并拖动来放大和缩小QGraphicsView,就像你在Maya和Nuke等图形应用程序中看到的那样。有很多关于使用鼠标滚轮的信息,但我还没有找到任何与拖动缩放相关的内容。

有没有一种简单的方法可以做到这一点,或者我是否需要推出自己的"锚点#34;实现

下面的方法可以正常工作,但是当我拖动缩放而不是看似放大和缩小空间中的固定点(单击鼠标以开始拖动缩放的点)时,视图跟随鼠标移动。

(这是我的更复杂的源代码中的一堆复制和粘贴。虽然它应该运行但它应该是说明性的)

def mousePressEvent(self, event):
    self.press_mouse_pos = event.pos()
    transform = self.transform()
    self.press_translate = [transform.m31(), transform.m32()]
    self.press_scale = transform.m11()

    if event.button() == QtCore.Qt.RightButton and \
                    event.modifiers() == QtCore.Qt.AltModifier:
        self.scaling = True
        event.accept()
    else:
        super(GraphView, self).mousePressEvent(event)

def mouseMoveEvent(self, event):
    if self.scaling:
        delta_pos = event.pos() - self.press_mouse_pos
        amount = delta_pos.x() + delta_pos.y()
        speed = 0.001
        scl = self.press_scale - (amount * speed)
        scl = min(1.0, max(scl, 0.1))  # Clamp so we don't go to far in or out

        transform = QtGui.QTransform(
            scl, 0, 0,
            0, scl, 0,
            self.press_translate[0], self.press_translate[1], 1
        )

        # If interactive is True then some double calculations are triggered
        prev_interactive_state = self.isInteractive()
        prev_anchor_mode = self.transformationAnchor()

        self.setInteractive(False)
        self.setTransformationAnchor(QtGui.QGraphicsView.AnchorUnderMouse)

        self.setTransform(transform)

        self.setInteractive(prev_interactive_state)
        self.setTransformationAnchor(prev_anchor_mode)
    else:
        super(GraphView, self).mouseMoveEvent(event)

def mouseReleaseEvent(self, event):
    self.scaling = False
    super(GraphView, self).mouseReleaseEvent(event)

1 个答案:

答案 0 :(得分:1)

改变这个:

Mozilla/5.0

那个:

let url = URL(string: "https://www.instagram.com/spacex/?__a=1")
let request = NSMutableURLRequest(url: url)
request.setValue("Mozilla/5.0", forHTTPHeaderField: "User-Agent")
request.setValue("no-cache", forHTTPHeaderField: "Cache-Control")
request.httpMethod = "GET"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
let session = URLSession.shared

DispatchQueue.global(qos: .background).async {
  let requestData = session.dataTask(with: request as URLRequest) { (data, response, error) -> Void in
    if let error = error {
      print("Error @ loadInstagram(): \(String(describing: error))")
      return
    }
    
    if let data = data {
      self.processInstagram(data: data) // function for processing the json data received
    } else {
      print("Error - missing data @ loadInstagram()")
    }
  }
  requestData.resume()
}

self.setTransformationAnchor(QtGui.QGraphicsView.AnchorUnderMouse) 是一个被转换的锚点; self.setTransformationAnchor(QtGui.QGraphicsView.NoAnchor) 确保与当前(应用变换时)鼠标位置对应的场景点保持未平移。