python - 如何将对象捕捉到 QGraphicsScene 中的网格?
问题描述
QGraphicsItem.ItemIsMovable
此代码通过使用标志实现了用鼠标移动对象的能力。但是如何使对象快速移动到网格?
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())
解决方案
推荐阅读
- unity3d - Unity - 围绕 2D 中的点旋转对象
- java - Android手机中Android Keystore的目录(路径)
- python - QT5 + Pytest - 将控制台输出重定向到小部件,最终只重定向部分数据
- javascript - app.use(express.static(path.join(__dirname))) 显然在我的快递服务器上不起作用
- angularjs - 在 ng-admin 创建视图的顶部添加一个链接?
- javascript - 动态 HTML 复选框上的“全选”复选框
- robotics - 在 Pepper 中,如何备份并擦除现有包?
- python - 从特殊字符列表中提取整数
- sql - 在 Oracle SQL 中搜索多个字符串
- vba - 如何在vba中定义公式?