Qrubberband.geometry().intersects(???) How To Find Intersecting Images In Qgraphicsscene?
I found few codes which demonstrates intersects, but it was mainly buttons. Something like this: for child in self.findChildren(QPushButton): if rect.intersects(child.geometry(
Solution 1:
If you are using the QRubberBand that has the QGraphicsView you have to use the rubberBandChanged signal and next to the items method you get the items that are below the QRubberBand.
from PyQt5 import QtCore, QtGui, QtWidgets
import random
defcreate_pixmap():
pixmap = QtGui.QPixmap(100, 100)
pixmap.fill(QtGui.QColor(*random.sample(range(255), 3)))
return pixmap
classGraphicsView(QtWidgets.QGraphicsView):
def__init__(self, parent=None):
super(GraphicsView, self).__init__(parent)
self.setScene(QtWidgets.QGraphicsScene(self))
self.setDragMode(QtWidgets.QGraphicsView.RubberBandDrag)
self.rubberBandChanged.connect(self.on_rubberBandChanged)
for _ inrange(5):
item = QtWidgets.QGraphicsPixmapItem(create_pixmap())
item.setPos(*random.sample(range(500), 2))
self.scene().addItem(item)
@QtCore.pyqtSlot("QRect", "QPointF", "QPointF")defon_rubberBandChanged(
self, rubberBandRect, fromScenePoint, toScenePoint
):
r = QtCore.QRectF(fromScenePoint, toScenePoint)
selected = self.items(rubberBandRect)
print(selected)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
w = GraphicsView()
w.resize(640, 480)
w.show()
sys.exit(app.exec_())
If you are using another QRubberBand the logic is similar to that since you must use the items() method of QGraphicsView
from PyQt5 import QtCore, QtGui, QtWidgets
import random
defcreate_pixmap():
pixmap = QtGui.QPixmap(100, 100)
pixmap.fill(QtGui.QColor(*random.sample(range(255), 3)))
return pixmap
classGraphicsView(QtWidgets.QGraphicsView):
def__init__(self, parent=None):
super(GraphicsView, self).__init__(parent)
self.setScene(QtWidgets.QGraphicsScene(self))
self._rubberBand = QtWidgets.QRubberBand(
QtWidgets.QRubberBand.Rectangle, self.viewport()
)
self._rubberBand.hide()
self._origin = QtCore.QPoint()
for _ inrange(5):
item = QtWidgets.QGraphicsPixmapItem(create_pixmap())
item.setPos(*random.sample(range(500), 2))
self.scene().addItem(item)
defmousePressEvent(self, event):
self._origin = event.pos()
self._rubberBand.setGeometry(QtCore.QRect(self._origin, QtCore.QSize()))
self._rubberBand.show()
super(GraphicsView, self).mousePressEvent(event)
defmouseMoveEvent(self, event):
self._rubberBand.setGeometry(
QtCore.QRect(self._origin, event.pos()).normalized()
)
defmouseReleaseEvent(self, event):
self._rubberBand.setGeometry(
QtCore.QRect(self._origin, event.pos()).normalized()
)
selected = self.items(self._rubberBand.geometry())
print(selected)
self._rubberBand.hide()
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
w = GraphicsView()
w.resize(640, 480)
w.show()
sys.exit(app.exec_())
Post a Comment for "Qrubberband.geometry().intersects(???) How To Find Intersecting Images In Qgraphicsscene?"