CustomGraphicsView

  1# CustomGraphicsView.py
  2
  3from PySide6.QtWidgets import QGraphicsView, QMenu, QGraphicsProxyWidget
  4from PySide6.QtGui import QAction, QPixmap, QPainter
  5from PySide6.QtCore import Qt, QPointF, QElapsedTimer
  6from NodeData import NodeData
  7from Node import Node
  8from Edge import Edge
  9from NodeLayout import NodeLayout  # Make sure to import NodeLayout
 10
 11class CustomGraphicsView(QGraphicsView):
 12    def __init__(self, scene, main_window):
 13        super().__init__(scene)
 14        self.setDragMode(QGraphicsView.NoDrag)
 15        self._dragging = False
 16        self._last_mouse_pos = QPointF()
 17        self.main_window = main_window  # Reference to the MainWindow
 18        self.timer = QElapsedTimer()  # Initialize the timer
 19        self.right_clicked_item = None
 20
 21    def mousePressEvent(self, event):
 22        if event.button() == Qt.RightButton:
 23            self._last_mouse_pos = event.pos()
 24            self.timer.start()  # Start the timer
 25
 26            # Check if the right-click is on an Edge or a Node
 27            item = self.itemAt(event.pos())
 28            while item and not isinstance(item, (Node, Edge)) and isinstance(item, (QGraphicsProxyWidget, NodeLayout)):
 29                item = item.parentItem()
 30
 31            if isinstance(item, Edge):
 32                self.right_clicked_item = item
 33            elif isinstance(item, Node):
 34                self.right_clicked_item = item
 35            else:
 36                self.right_clicked_item = None
 37
 38        super().mousePressEvent(event)
 39
 40    def mouseMoveEvent(self, event):
 41        if event.buttons() & Qt.RightButton:
 42            delta = event.pos() - self._last_mouse_pos
 43            self._last_mouse_pos = event.pos()
 44            self.horizontalScrollBar().setValue(self.horizontalScrollBar().value() - delta.x())
 45            self.verticalScrollBar().setValue(self.verticalScrollBar().value() - delta.y())
 46            self._dragging = True
 47        else:
 48            super().mouseMoveEvent(event)
 49
 50    def mouseReleaseEvent(self, event):
 51        if event.button() == Qt.RightButton:
 52            elapsed_time = self.timer.elapsed()  # Get the elapsed time
 53            if elapsed_time < 170:  # If the right-click was shorter than 170 ms
 54                self.show_context_menu(event.pos())
 55            self._dragging = False
 56        else:
 57            super().mouseReleaseEvent(event)
 58
 59    def add_node(self, position):
 60        unique_id = f"uniq_id_{self.scene().node_counter}"
 61        node_data = NodeData(name="Node", uniq_id=unique_id)
 62        node = Node(node_data)
 63        self.scene().addItem(node)
 64        node.setPos(position)  # Set the node position to the right-click position
 65        self.scene().node_counter += 1  # Increment the counter
 66        self.update_map_view()
 67
 68    def remove_node(self):
 69        if self.right_clicked_item and isinstance(self.right_clicked_item, Node):
 70            self.right_clicked_item.remove_node()
 71            self.right_clicked_item = None
 72
 73    def remove_edge(self):
 74        if self.right_clicked_item and isinstance(self.right_clicked_item, Edge):
 75            self.right_clicked_item.remove()
 76            self.right_clicked_item = None
 77
 78    def update_map_view(self):
 79        rect = self.scene().sceneRect()
 80        pixmap = QPixmap(int(rect.width()), int(rect.height()))
 81        pixmap.fill(Qt.transparent)
 82        painter = QPainter(pixmap)
 83        self.scene().render(painter)
 84        painter.end()
 85        self.main_window.map_view.update_map(pixmap)  # Update the map view in the MainWindow
 86
 87    def show_context_menu(self, position):
 88        self.right_click_position = self.mapToScene(position)
 89        context_menu = QMenu(self)
 90
 91        if isinstance(self.right_clicked_item, Edge):
 92            remove_edge_action = QAction("Remove Edge", self)
 93            remove_edge_action.triggered.connect(self.remove_edge)
 94            context_menu.addAction(remove_edge_action)
 95        elif isinstance(self.right_clicked_item, Node):
 96            remove_node_action = QAction("Remove Node", self)
 97            remove_node_action.triggered.connect(self.remove_node)
 98            context_menu.addAction(remove_node_action)
 99        else:
100            add_node_action = QAction("Add Node", self)
101            add_node_action.triggered.connect(lambda: self.add_node(self.right_click_position))
102            context_menu.addAction(add_node_action)
103
104        context_menu.exec(self.mapToGlobal(position))
class CustomGraphicsView(PySide6.QtWidgets.QGraphicsView):
 12class CustomGraphicsView(QGraphicsView):
 13    def __init__(self, scene, main_window):
 14        super().__init__(scene)
 15        self.setDragMode(QGraphicsView.NoDrag)
 16        self._dragging = False
 17        self._last_mouse_pos = QPointF()
 18        self.main_window = main_window  # Reference to the MainWindow
 19        self.timer = QElapsedTimer()  # Initialize the timer
 20        self.right_clicked_item = None
 21
 22    def mousePressEvent(self, event):
 23        if event.button() == Qt.RightButton:
 24            self._last_mouse_pos = event.pos()
 25            self.timer.start()  # Start the timer
 26
 27            # Check if the right-click is on an Edge or a Node
 28            item = self.itemAt(event.pos())
 29            while item and not isinstance(item, (Node, Edge)) and isinstance(item, (QGraphicsProxyWidget, NodeLayout)):
 30                item = item.parentItem()
 31
 32            if isinstance(item, Edge):
 33                self.right_clicked_item = item
 34            elif isinstance(item, Node):
 35                self.right_clicked_item = item
 36            else:
 37                self.right_clicked_item = None
 38
 39        super().mousePressEvent(event)
 40
 41    def mouseMoveEvent(self, event):
 42        if event.buttons() & Qt.RightButton:
 43            delta = event.pos() - self._last_mouse_pos
 44            self._last_mouse_pos = event.pos()
 45            self.horizontalScrollBar().setValue(self.horizontalScrollBar().value() - delta.x())
 46            self.verticalScrollBar().setValue(self.verticalScrollBar().value() - delta.y())
 47            self._dragging = True
 48        else:
 49            super().mouseMoveEvent(event)
 50
 51    def mouseReleaseEvent(self, event):
 52        if event.button() == Qt.RightButton:
 53            elapsed_time = self.timer.elapsed()  # Get the elapsed time
 54            if elapsed_time < 170:  # If the right-click was shorter than 170 ms
 55                self.show_context_menu(event.pos())
 56            self._dragging = False
 57        else:
 58            super().mouseReleaseEvent(event)
 59
 60    def add_node(self, position):
 61        unique_id = f"uniq_id_{self.scene().node_counter}"
 62        node_data = NodeData(name="Node", uniq_id=unique_id)
 63        node = Node(node_data)
 64        self.scene().addItem(node)
 65        node.setPos(position)  # Set the node position to the right-click position
 66        self.scene().node_counter += 1  # Increment the counter
 67        self.update_map_view()
 68
 69    def remove_node(self):
 70        if self.right_clicked_item and isinstance(self.right_clicked_item, Node):
 71            self.right_clicked_item.remove_node()
 72            self.right_clicked_item = None
 73
 74    def remove_edge(self):
 75        if self.right_clicked_item and isinstance(self.right_clicked_item, Edge):
 76            self.right_clicked_item.remove()
 77            self.right_clicked_item = None
 78
 79    def update_map_view(self):
 80        rect = self.scene().sceneRect()
 81        pixmap = QPixmap(int(rect.width()), int(rect.height()))
 82        pixmap.fill(Qt.transparent)
 83        painter = QPainter(pixmap)
 84        self.scene().render(painter)
 85        painter.end()
 86        self.main_window.map_view.update_map(pixmap)  # Update the map view in the MainWindow
 87
 88    def show_context_menu(self, position):
 89        self.right_click_position = self.mapToScene(position)
 90        context_menu = QMenu(self)
 91
 92        if isinstance(self.right_clicked_item, Edge):
 93            remove_edge_action = QAction("Remove Edge", self)
 94            remove_edge_action.triggered.connect(self.remove_edge)
 95            context_menu.addAction(remove_edge_action)
 96        elif isinstance(self.right_clicked_item, Node):
 97            remove_node_action = QAction("Remove Node", self)
 98            remove_node_action.triggered.connect(self.remove_node)
 99            context_menu.addAction(remove_node_action)
100        else:
101            add_node_action = QAction("Add Node", self)
102            add_node_action.triggered.connect(lambda: self.add_node(self.right_click_position))
103            context_menu.addAction(add_node_action)
104
105        context_menu.exec(self.mapToGlobal(position))

QGraphicsView(self, parent: Optional[PySide6.QtWidgets.QWidget] = None) -> None QGraphicsView(self, scene: PySide6.QtWidgets.QGraphicsScene, parent: Optional[PySide6.QtWidgets.QWidget] = None) -> None

CustomGraphicsView(scene, main_window)
13    def __init__(self, scene, main_window):
14        super().__init__(scene)
15        self.setDragMode(QGraphicsView.NoDrag)
16        self._dragging = False
17        self._last_mouse_pos = QPointF()
18        self.main_window = main_window  # Reference to the MainWindow
19        self.timer = QElapsedTimer()  # Initialize the timer
20        self.right_clicked_item = None
main_window
timer
right_clicked_item
def mousePressEvent(self, event):
22    def mousePressEvent(self, event):
23        if event.button() == Qt.RightButton:
24            self._last_mouse_pos = event.pos()
25            self.timer.start()  # Start the timer
26
27            # Check if the right-click is on an Edge or a Node
28            item = self.itemAt(event.pos())
29            while item and not isinstance(item, (Node, Edge)) and isinstance(item, (QGraphicsProxyWidget, NodeLayout)):
30                item = item.parentItem()
31
32            if isinstance(item, Edge):
33                self.right_clicked_item = item
34            elif isinstance(item, Node):
35                self.right_clicked_item = item
36            else:
37                self.right_clicked_item = None
38
39        super().mousePressEvent(event)
def mouseMoveEvent(self, event):
41    def mouseMoveEvent(self, event):
42        if event.buttons() & Qt.RightButton:
43            delta = event.pos() - self._last_mouse_pos
44            self._last_mouse_pos = event.pos()
45            self.horizontalScrollBar().setValue(self.horizontalScrollBar().value() - delta.x())
46            self.verticalScrollBar().setValue(self.verticalScrollBar().value() - delta.y())
47            self._dragging = True
48        else:
49            super().mouseMoveEvent(event)
def mouseReleaseEvent(self, event):
51    def mouseReleaseEvent(self, event):
52        if event.button() == Qt.RightButton:
53            elapsed_time = self.timer.elapsed()  # Get the elapsed time
54            if elapsed_time < 170:  # If the right-click was shorter than 170 ms
55                self.show_context_menu(event.pos())
56            self._dragging = False
57        else:
58            super().mouseReleaseEvent(event)
def add_node(self, position):
60    def add_node(self, position):
61        unique_id = f"uniq_id_{self.scene().node_counter}"
62        node_data = NodeData(name="Node", uniq_id=unique_id)
63        node = Node(node_data)
64        self.scene().addItem(node)
65        node.setPos(position)  # Set the node position to the right-click position
66        self.scene().node_counter += 1  # Increment the counter
67        self.update_map_view()
def remove_node(self):
69    def remove_node(self):
70        if self.right_clicked_item and isinstance(self.right_clicked_item, Node):
71            self.right_clicked_item.remove_node()
72            self.right_clicked_item = None
def remove_edge(self):
74    def remove_edge(self):
75        if self.right_clicked_item and isinstance(self.right_clicked_item, Edge):
76            self.right_clicked_item.remove()
77            self.right_clicked_item = None
def update_map_view(self):
79    def update_map_view(self):
80        rect = self.scene().sceneRect()
81        pixmap = QPixmap(int(rect.width()), int(rect.height()))
82        pixmap.fill(Qt.transparent)
83        painter = QPainter(pixmap)
84        self.scene().render(painter)
85        painter.end()
86        self.main_window.map_view.update_map(pixmap)  # Update the map view in the MainWindow
def show_context_menu(self, position):
 88    def show_context_menu(self, position):
 89        self.right_click_position = self.mapToScene(position)
 90        context_menu = QMenu(self)
 91
 92        if isinstance(self.right_clicked_item, Edge):
 93            remove_edge_action = QAction("Remove Edge", self)
 94            remove_edge_action.triggered.connect(self.remove_edge)
 95            context_menu.addAction(remove_edge_action)
 96        elif isinstance(self.right_clicked_item, Node):
 97            remove_node_action = QAction("Remove Node", self)
 98            remove_node_action.triggered.connect(self.remove_node)
 99            context_menu.addAction(remove_node_action)
100        else:
101            add_node_action = QAction("Add Node", self)
102            add_node_action.triggered.connect(lambda: self.add_node(self.right_click_position))
103            context_menu.addAction(add_node_action)
104
105        context_menu.exec(self.mapToGlobal(position))
staticMetaObject = PySide6.QtCore.QMetaObject("CustomGraphicsView" inherits "QGraphicsView": )
Inherited Members
PySide6.QtWidgets.QGraphicsView
alignment
backgroundBrush
cacheMode
centerOn
contextMenuEvent
dragEnterEvent
dragLeaveEvent
dragMode
dragMoveEvent
drawBackground
drawForeground
drawItems
dropEvent
ensureVisible
event
fitInView
focusInEvent
focusNextPrevChild
focusOutEvent
foregroundBrush
inputMethodEvent
inputMethodQuery
invalidateScene
isInteractive
isTransformed
itemAt
items
keyPressEvent
keyReleaseEvent
mapFromScene
mapToScene
mouseDoubleClickEvent
optimizationFlags
paintEvent
render
renderHints
resetCachedContent
resetTransform
resizeAnchor
resizeEvent
rotate
rubberBandRect
rubberBandSelectionMode
scale
scene
sceneRect
scrollContentsBy
setAlignment
setBackgroundBrush
setCacheMode
setDragMode
setForegroundBrush
setInteractive
setOptimizationFlag
setOptimizationFlags
setRenderHint
setRenderHints
setResizeAnchor
setRubberBandSelectionMode
setScene
setSceneRect
setTransform
setTransformationAnchor
setViewportUpdateMode
setupViewport
shear
showEvent
sizeHint
transform
transformationAnchor
translate
updateScene
updateSceneRect
viewportEvent
viewportTransform
viewportUpdateMode
wheelEvent
ViewportAnchor
CacheModeFlag
DragMode
ViewportUpdateMode
OptimizationFlag
rubberBandChanged
PySide6.QtWidgets.QAbstractScrollArea
addScrollBarWidget
cornerWidget
eventFilter
horizontalScrollBar
horizontalScrollBarPolicy
maximumViewportSize
minimumSizeHint
scrollBarWidgets
setCornerWidget
setHorizontalScrollBar
setHorizontalScrollBarPolicy
setSizeAdjustPolicy
setVerticalScrollBar
setVerticalScrollBarPolicy
setViewport
setViewportMargins
sizeAdjustPolicy
verticalScrollBar
verticalScrollBarPolicy
viewport
viewportMargins
viewportSizeHint
SizeAdjustPolicy
PySide6.QtWidgets.QFrame
changeEvent
drawFrame
frameRect
frameShadow
frameShape
frameStyle
frameWidth
initStyleOption
lineWidth
midLineWidth
setFrameRect
setFrameShadow
setFrameShape
setFrameStyle
setLineWidth
setMidLineWidth
Shape
Shadow
StyleMask
PySide6.QtWidgets.QWidget
acceptDrops
accessibleDescription
accessibleName
actionEvent
actions
activateWindow
addAction
addActions
adjustSize
autoFillBackground
backgroundRole
backingStore
baseSize
childAt
childrenRect
childrenRegion
clearFocus
clearMask
close
closeEvent
contentsMargins
contentsRect
contextMenuPolicy
create
createWinId
createWindowContainer
cursor
destroy
devType
effectiveWinId
ensurePolished
enterEvent
find
focusNextChild
focusPolicy
focusPreviousChild
focusProxy
focusWidget
font
fontInfo
fontMetrics
foregroundRole
frameGeometry
frameSize
geometry
grab
grabGesture
grabKeyboard
grabMouse
grabShortcut
graphicsEffect
graphicsProxyWidget
hasFocus
hasHeightForWidth
hasMouseTracking
hasTabletTracking
height
heightForWidth
hide
hideEvent
initPainter
inputMethodHints
insertAction
insertActions
internalWinId
isActiveWindow
isAncestorOf
isEnabled
isEnabledTo
isFullScreen
isHidden
isLeftToRight
isMaximized
isMinimized
isModal
isRightToLeft
isTopLevel
isVisible
isVisibleTo
isWindow
isWindowModified
keyboardGrabber
layout
layoutDirection
leaveEvent
locale
lower
mapFrom
mapFromGlobal
mapFromParent
mapTo
mapToGlobal
mapToParent
mask
maximumHeight
maximumSize
maximumWidth
metric
minimumHeight
minimumSize
minimumWidth
mouseGrabber
move
moveEvent
nativeEvent
nativeParentWidget
nextInFocusChain
normalGeometry
overrideWindowFlags
overrideWindowState
paintEngine
palette
parentWidget
pos
previousInFocusChain
raise_
rect
redirected
releaseKeyboard
releaseMouse
releaseShortcut
removeAction
repaint
resize
restoreGeometry
saveGeometry
screen
scroll
setAcceptDrops
setAccessibleDescription
setAccessibleName
setAttribute
setAutoFillBackground
setBackgroundRole
setBaseSize
setContentsMargins
setContextMenuPolicy
setCursor
setDisabled
setEnabled
setFixedHeight
setFixedSize
setFixedWidth
setFocus
setFocusPolicy
setFocusProxy
setFont
setForegroundRole
setGeometry
setGraphicsEffect
setHidden
setInputMethodHints
setLayout
setLayoutDirection
setLocale
setMask
setMaximumHeight
setMaximumSize
setMaximumWidth
setMinimumHeight
setMinimumSize
setMinimumWidth
setMouseTracking
setPalette
setParent
setScreen
setShortcutAutoRepeat
setShortcutEnabled
setSizeIncrement
setSizePolicy
setStatusTip
setStyle
setStyleSheet
setTabOrder
setTabletTracking
setToolTip
setToolTipDuration
setUpdatesEnabled
setVisible
setWhatsThis
setWindowFilePath
setWindowFlag
setWindowFlags
setWindowIcon
setWindowIconText
setWindowModality
setWindowModified
setWindowOpacity
setWindowRole
setWindowState
setWindowTitle
sharedPainter
show
showFullScreen
showMaximized
showMinimized
showNormal
size
sizeIncrement
sizePolicy
stackUnder
statusTip
style
styleSheet
tabletEvent
testAttribute
toolTip
toolTipDuration
topLevelWidget
underMouse
ungrabGesture
unsetCursor
unsetLayoutDirection
unsetLocale
update
updateGeometry
updateMicroFocus
updatesEnabled
visibleRegion
whatsThis
width
winId
window
windowFilePath
windowFlags
windowHandle
windowIcon
windowIconText
windowModality
windowOpacity
windowRole
windowState
windowTitle
windowType
x
y
RenderFlag
windowTitleChanged
windowIconChanged
windowIconTextChanged
customContextMenuRequested
PySide6.QtCore.QObject
blockSignals
childEvent
children
connect
connectNotify
customEvent
deleteLater
disconnect
disconnectNotify
dumpObjectInfo
dumpObjectTree
dynamicPropertyNames
emit
findChild
findChildren
inherits
installEventFilter
isQuickItemType
isSignalConnected
isWidgetType
isWindowType
killTimer
metaObject
moveToThread
objectName
parent
property
receivers
removeEventFilter
sender
senderSignalIndex
setObjectName
setProperty
signalsBlocked
startTimer
thread
timerEvent
tr
destroyed
objectNameChanged
PySide6.QtGui.QPaintDevice
colorCount
depth
devicePixelRatio
devicePixelRatioF
devicePixelRatioFScale
heightMM
logicalDpiX
logicalDpiY
paintingActive
physicalDpiX
physicalDpiY
widthMM
painters
PaintDeviceMetric