使用QGraphicsScene中的selectionChanged信号在所选项目周围添加

时间:2016-07-15 03:11:42

标签: python qt pyqt qgraphicsscene selectionchanged

我正在尝试在场景中选择的项目周围绘制一个矩形(通过RubberBandDrag或ctrl +单击每个项目)。

为了做到这一点,我已经对QGraphicsScene进行了子类化并重新实现了selectionChanged方法,在所选区域周围添加了一个QGraphicsRectItem,但由于某种原因,当选择或取消选择项时,不会调用此方法在场景中。我确保这些物品实际上是可选择的。

以下是我尝试做的最小例子:

from PyQt4.QtGui import *
from PyQt4.QtCore import *
import sys  

class DiagramScene(QGraphicsScene):

    def __init__(self, parent=None):
        super().__init__(parent)

        self.selRect = None

    def selectionChanged(self):
        area = self.selectionArea().boundingRect()
        pen = QPen()
        pen.setColor(Qt.black)
        pen.setStyle(Qt.DashLine)

        self.selRect = self.addRect(area, pen)


if __name__ == "__main__":

    app = QApplication(sys.argv)

    view = QGraphicsView()
    view.setDragMode(QGraphicsView.RubberBandDrag)

    scene = DiagramScene()

    scene.setSceneRect(0, 0, 500, 500)

    rect1 = scene.addRect(20, 20, 100, 50)
    rect2 = scene.addRect(80, 80, 100, 50)
    rect3 = scene.addRect(140, 140, 100, 50)

    rect1.setFlag(QGraphicsItem.ItemIsSelectable, True)
    rect2.setFlag(QGraphicsItem.ItemIsSelectable, True)
    rect3.setFlag(QGraphicsItem.ItemIsSelectable, True)

    view.setScene(scene)
    view.show()

    sys.exit(app.exec_())

1 个答案:

答案 0 :(得分:1)

selectionChanged是一个信号,而不是您必须实施的方法。您需要做的是将此信号连接到插槽以及插槽中的实现,因此无论何时发出信号,您的代码都会被执行:

from PyQt4.QtGui import *
from PyQt4.QtCore import *
import sys  

class DiagramScene(QGraphicsScene):

    def __init__(self, parent=None):
        super().__init__(parent)
        self.selRect = None
        self.selectionChanged.connect(self.onSelectionChanged)

    @pyqtSlot()
    def onSelectionChanged(self):
        area = self.selectionArea().boundingRect()
        pen = QPen()
        pen.setColor(Qt.black)
        pen.setStyle(Qt.DashLine)
        self.selRect = self.addRect(area, pen)


if __name__ == "__main__":

    app = QApplication(sys.argv)

    view = QGraphicsView()
    view.setDragMode(QGraphicsView.RubberBandDrag)

    scene = DiagramScene()

    scene.setSceneRect(0, 0, 500, 500)

    rect1 = scene.addRect(20, 20, 100, 50)
    rect2 = scene.addRect(80, 80, 100, 50)
    rect3 = scene.addRect(140, 140, 100, 50)

    rect1.setFlag(QGraphicsItem.ItemIsSelectable, True)
    rect2.setFlag(QGraphicsItem.ItemIsSelectable, True)
    rect3.setFlag(QGraphicsItem.ItemIsSelectable, True)

    view.setScene(scene)
    view.show()

    sys.exit(app.exec_())