1

This code implements the ability to move objects with the mouse by using the QGraphicsItem.ItemIsMovable flag. But how to make objects move with a snap to a grid?

from PyQt5 import QtGui
from PyQt5.QtWidgets import QApplication, QMainWindow, QGraphicsScene, QGraphicsView, QGraphicsItem
from PyQt5.QtGui import QPen, QBrush
from PyQt5.Qt import Qt

import sys


class Window(QMainWindow):
    def __init__(self):
        super().__init__()

        self.title = "PyQt5 QGraphicView"
        self.top = 200
        self.left = 500
        self.width = 600
        self.height = 500

        self.InitWindow()

    def InitWindow(self):
        self.setWindowIcon(QtGui.QIcon("icon.png"))
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)

        self.createGraphicView()

        self.show()

    def createGraphicView(self):
        self.scene = QGraphicsScene()
        self.greenBrush = QBrush(Qt.green)
        self.grayBrush = QBrush(Qt.gray)

        self.pen = QPen(Qt.red)

        graphicView = QGraphicsView(self.scene, self)
        graphicView.setGeometry(0, 0, 600, 500)

        self.shapes()

    def shapes(self):
        ellipse = self.scene.addEllipse(20, 20, 200, 200, self.pen, self.greenBrush)
        rect = self.scene.addRect(-100, -100, 200, 200, self.pen, self.grayBrush)

        ellipse.setFlag(QGraphicsItem.ItemIsMovable)
        rect.setFlag(QGraphicsItem.ItemIsMovable)


App = QApplication(sys.argv)
window = Window()
sys.exit(App.exec())

fromgate
  • 21
  • 3
  • 1
    mmm, I don't understand you (maybe the language is my limitation), could you explain what you want – eyllanesc May 11 '20 at 13:44
  • @eyllanesc This video shows that when I turn on the "Snap" option, the windows begin to move with a snap to the grid. So, I want to do the same with the objects in ```QGraphicsScene```. It doesn't matter what the application is in the video. I think it’s a good example. https://drive.google.com/open?id=1noC5_GH0ZPPea4O4p-_d-yPFwvx_QtwF – fromgate May 12 '20 at 18:05

0 Answers0