I want to create a GUI using Pyside6. A a menu pop up when the user right click on a QGraphicsRectItem. All of these is currently working. However, the QGraphicsView can be big and a scollbar appear. In this case, the menu will pop up with translation related to the scrollbar position. Here is a simple exemple :

import sys
from PySide6.QtWidgets import QApplication, QGraphicsView, QGraphicsScene, QGraphicsRectItem, QMenu
from PySide6.QtCore import *

class MyRectItem(QGraphicsRectItem):
  def __init__(self, *args, **kwargs):
    super(MyRectItem, self).__init__(*args, **kwargs)

def contextMenuEvent(self, event):
    menu = QMenu()

    action1 = menu.addAction("Option 1")
    action2 = menu.addAction("Option 2")
    action3 = menu.addAction("Option 3")

    # Use mapToScene on the event position to get the position in scene coordinates
    scene_pos = self.mapToScene(event.pos())
    global_pos = self.scene().views()[0].mapToGlobal(scene_pos.toPoint())
    print(self.scene().views()[0].horizontalScrollBar)
    print(self.scene().views()[0].verticalScrollBar)


    action = menu.exec(global_pos)

    if action == action1:
        print("Option 1 selected")
    elif action == action2:
        print("Option 2 selected")
    elif action == action3:
        print("Option 3 selected")


class MyGraphicsView(QGraphicsView):
  def __init__(self, scene):
    super(MyGraphicsView, self).__init__(scene)

  def mousePressEvent(self, event):
    if event.button() == 2:  # Right mouse button
        item = self.itemAt(event.pos())
        if isinstance(item, MyRectItem):
            item.contextMenuEvent(event)
    super(MyGraphicsView, self).mousePressEvent(event)


def main():
  app = QApplication(sys.argv)

  scene = QGraphicsScene()
  rect_item = MyRectItem(500, 500, 100, 100)
  scene.addItem(rect_item)

  view = MyGraphicsView(scene)
  view.setSceneRect(0, 0, 800, 800)  # Adjust scene rect as needed
  view.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOn)  # Enable horizontal scrollbar
  view.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)    # Enable vertical scrollbar
  view.show()

  sys.exit(app.exec())


if __name__ == "__main__":
  main()

When I click on the item with scrollbar at minimal position, the menu pop up correctly :

Correct exemple

When I click at the same position on the item, but with the scrollbar at the maximal position, the menu pop up with translation :

Incorrect example

Do you see a possible correction?

0

There are 0 answers