BIG阳
如果您正在使用具有 QGraphicsView 的 QRubberBand,则必须使用 RubberBandChanged 信号,并且在 items 方法旁边,您将获得 QRubberBand 下方的项目。from PyQt5 import QtCore, QtGui, QtWidgetsimport randomdef create_pixmap(): pixmap = QtGui.QPixmap(100, 100) pixmap.fill(QtGui.QColor(*random.sample(range(255), 3))) return pixmapclass GraphicsView(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 _ in range(5): item = QtWidgets.QGraphicsPixmapItem(create_pixmap()) item.setPos(*random.sample(range(500), 2)) self.scene().addItem(item) @QtCore.pyqtSlot("QRect", "QPointF", "QPointF") def on_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_())如果您使用另一个 QRubberBand,则逻辑与此类似,因为您必须使用QGraphicsView的items()方法from PyQt5 import QtCore, QtGui, QtWidgetsimport randomdef create_pixmap(): pixmap = QtGui.QPixmap(100, 100) pixmap.fill(QtGui.QColor(*random.sample(range(255), 3))) return pixmapclass GraphicsView(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 _ in range(5): item = QtWidgets.QGraphicsPixmapItem(create_pixmap()) item.setPos(*random.sample(range(500), 2)) self.scene().addItem(item) def mousePressEvent(self, event): self._origin = event.pos() self._rubberBand.setGeometry(QtCore.QRect(self._origin, QtCore.QSize())) self._rubberBand.show() super(GraphicsView, self).mousePressEvent(event) def mouseMoveEvent(self, event): self._rubberBand.setGeometry( QtCore.QRect(self._origin, event.pos()).normalized() ) def mouseReleaseEvent(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_())