gpt4 book ai didi

qt - QGraphicsView:如何使橡皮筋选择仅出现在鼠标左键上?

转载 作者:行者123 更新时间:2023-12-04 16:30:52 25 4
gpt4 key购买 nike

我想做一个 QGraphicsScene并显示在 QGraphicsView .我想通过鼠标中键滚动场景并通过左键选择橡皮筋。但我不知道如何使橡皮筋选择仅通过鼠标左键出现。

这是我的代码:

# -*- coding: utf-8 -*-

import os, sys

from PyQt5 import QtWidgets, QtCore, QtGui, QtSvg

class MegaSceneView(QtWidgets.QGraphicsView):
def __init__(self, parent=None):
super(MegaSceneView, self).__init__(parent)
self._scale_factor = 1.0

self._scale_by = 1.2
self.setAcceptDrops(True)

self.setRenderHint(QtGui.QPainter.Antialiasing)
self.setMouseTracking(True)
self.setRubberBandSelectionMode(QtCore.Qt.IntersectsItemShape)
self.setDragMode(QtWidgets.QGraphicsView.RubberBandDrag)

self._prev_mouse_scene_pos = None


def mousePressEvent(self, event):
if (event.buttons() & QtCore.Qt.MidButton) != QtCore.Qt.NoButton:
self._prev_mouse_scene_pos = (event.pos())
super(MegaSceneView, self).mousePressEvent(event)

def mouseReleaseEvent(self, event):
super(MegaSceneView, self).mouseReleaseEvent(event)
self._prev_mouse_scene_pos = None

def mouseMoveEvent(self, event):
super(MegaSceneView, self).mouseMoveEvent(event)

if (event.buttons() & QtCore.Qt.MidButton) != QtCore.Qt.NoButton:
cur_mouse_pos = (event.pos())
if self._prev_mouse_scene_pos is not None:
delta_x = cur_mouse_pos.x() - self._prev_mouse_scene_pos.x()
delta_y = cur_mouse_pos.y() - self._prev_mouse_scene_pos.y()

self.horizontalScrollBar().setValue(self.horizontalScrollBar().value() - delta_x)
self.verticalScrollBar().setValue(self.verticalScrollBar().value() - delta_y)

self._prev_mouse_scene_pos = (event.pos())

if __name__ == "__main__":

app = QtWidgets.QApplication(sys.argv)

mega_view = MegaSceneView()

mega_scene = QtWidgets.QGraphicsScene(-500, -500, 1000, 1000)
# mega_scene = QtWidgets.QGraphicsScene()

rect_item_1 = QtWidgets.QGraphicsRectItem(-30, -20, 60, 40)
mega_scene.addItem(rect_item_1)

rect_item_2 = QtWidgets.QGraphicsRectItem(-20, -30, 40, 60)
mega_scene.addItem(rect_item_2)
rect_item_2.setPos(300, 200)

mega_view.setScene(mega_scene)
mega_view.show()

sys.exit(app.exec_())

我应该添加什么才能使橡皮筋仅通过左键出现?

最佳答案

没有内置的方法可以做到这一点。您将需要对 mousePressEvent 进行子类化, mouseMoveEvent , 和 mouseReleaseEvent用于您的图形 View 并自己创建可见的橡皮筋。 ( QRubberBand 对此很有效。)当用户释放鼠标时,您需要将橡皮筋范围转换为场景坐标并调用 QGraphicsScene::setSelectionArea .

关于qt - QGraphicsView:如何使橡皮筋选择仅出现在鼠标左键上?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42692885/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com