【问题标题】:Cannot properly position QGraphicsRectItem in scene无法在场景中正确定位 QGraphicsRectItem
【发布时间】:2016-11-18 22:59:06
【问题描述】:

我这辈子都无法解决这个问题,但我已将其归结为一个自给自足的问题。

我想要做的是在QGraphicsScene 中选择的项目周围画一个QGraphicsRectItem。绘制矩形后,它可以以将所有项目一起移动的方式移动。我已经查看了QGraphicsItemGroup,并认为这在我的实际用例中是不可行的。

问题:我已经能够完成上面提到的所有事情,除了我无法正确定位 rect 项目,即它的大小正确并通过移动它,所有项目都被移动,但它没有与所选项目的统一边界矩形对齐。我试图将所有内容都保留在场景坐标中,所以我不确定为什么会有偏移。

为什么会出现偏移,如何缓解?

这是可以通过 ctrl-click 或橡皮筋选择测试的可运行代码(我知道这是大量代码,但相关部分已注释)。

#####The line where the position of the rect item is set is marked like this#####

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


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

        self.selBox = None
        self.selectionChanged.connect(self.onSelectionChange)

    @pyqtSlot()
    def onSelectionChange(self):
        count = 0
        items = self.selectedItems()

        # Get bounding rect of all selected Items
        for item in self.selectedItems():
            if count == 0:
                rect = item.mapRectToScene(item.boundingRect())
            else:
                rect = rect.unite(item.mapRectToScene(item.boundingRect()))
            count += 1

        if count > 0:
            if self.selBox:
                # Update selBox if items are selected and already exists
                self.selBox.setRect(rect)
                self.selBox.items = items
            else:
                # Instantiate selBox if items are selected and does not already exist
                self.selBox = DiagramSelBox(rect, items)
                ##### Set position of selBox to topLeft corner of united rect #####
                self.selBox.setPos(rect.topLeft())
                self.addItem(self.selBox)
        elif self.selBox:
            # Remove selBox from scene if no items are selected and box is drawn
            self.removeItem(self.selBox)
            del self.selBox
            self.selBox = None


class DiagramSelBox(QGraphicsRectItem):
    def __init__(self, bounds, items, parent=None, scene=None):
        super().__init__(bounds, parent, scene)

        self.setFlag(QGraphicsItem.ItemIsSelectable, True)
        self.pressPos = None
        self.items = items

    def paint(self, painter, option, widget=None):
        pen = QPen(Qt.DashLine)
        painter.setPen(pen)
        painter.drawRect(self.rect())

    def mousePressEvent(self, e):
        # Get original position of selBox when clicked
        self.pressPos = self.pos()
        # mouseEvent is not passed on to scene so item selection
        # does not change

    def mouseMoveEvent(self, e):
        super().mouseMoveEvent(e)
        if self.pressPos:
            # Move selBox is original position is set
            newPos = self.mapToScene(e.pos()) - self.rect().center()
            self.setPos(newPos)

    def mouseReleaseEvent(self, e):
        # Update position of all selected items
        change = self.scenePos() - self.pressPos
        for item in self.items:
            item.moveBy(change.x(), change.y())

        super().mouseReleaseEvent(e)


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_())

【问题讨论】:

    标签: python c++ qt pyqt qgraphicsitem


    【解决方案1】:

    我没有安装 PyQt,但我遇到了与常规 QT 和 QGraphicsRectItem 类似的问题。

    我认为您在坐标系方面混淆了一些东西。每个QGraphicsItem 的边界矩形都在本地坐标中。局部坐标中的点 (0,0) 出现在场景中由QGraphicsItem::pos() (scene-coordiantes) 给出的坐标上。

    QGraphicsRectItem 有点特别,因为我们通常根本不触摸pos(所以我们将其保留在 0,0)并将场景坐标中的矩形传递给setRectQGraphicsRectItem::setRect 基本上将边界矩形设置为传递的值。所以如果你根本不打电话给setPos(在onSelectionChange),而只将场景坐标传递给setRect,你应该没问题。

    DiagramSelBox 中的 mouseEvents 也需要调整。我的方法如下所示:

    1. mousePress:将e.pos(映射到场景)和self.rect.topLeft()之间的差异存储在self.diffPos中,并将self.rect.topLeft复制到self.startPos
    2. mouseMove:确保e.pos(映射到场景)和self.rect.topLeft()之间的差异保持不变,通过移动self.rect(使用self.diffPos进行计算)
    3. mouseRelease:移动项目self.rect.topLeft()self.startPos之间的差异。

    希望对您有所帮助。

    【讨论】:

    • 感谢您深入研究!我最终接受了您保留 (0, 0) 的建议,而是使用了 e.pos()mousePressEvent 之间的差异,然后是 mouseMoveEventmouseReleaset 甚至分别移动选择框和定位项目。跨度>
    猜你喜欢
    • 2016-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多