PyQt:用setRect()控制QGraphicsRectItem的位置

2024-09-28 04:24:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我第一次尝试PyQT,是为了最终创建一些数据的基本图形表示。
我目前正在尝试在QGraphicsRectItem内放入两个QGraphicsTextItem,对于我看到的一些结果我有一些疑问。在

class MyRect(QGraphicsRectItem):

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

        self.text_item  = QGraphicsTextItem('My Text Here', self)
        self.value_item = QGraphicsTextItem('My Value Here', self)
        self.text_item.setDefaultTextColor(QColor(Qt.blue))
        self.value_item.setDefaultTextColor(QColor(Qt.red))

        self.value_item.setPos(self.text_item.boundingRect().bottomLeft())

        width  = max(self.text_item.boundingRect().width(), self.value_item.boundingRect().width())
        height = self.text_item.boundingRect().height() + self.value_item.boundingRect().height()
        self.setRect(50, 50, width, height)


class MainFrame(QDialog):

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

        ### setting up the scene
        self.view = QGraphicsView()
        self.scene = QGraphicsScene(self)
        self.view.setScene(self.scene)
        self.scene.setSceneRect(0, 0, 500, 500)

        ### setting up MyRect
        my_rect = MyRect()

        self.scene.addItem(my_rect)

        layout = QHBoxLayout()
        layout.addWidget(self.view)
        self.setLayout(layout)

        self.setWindowTitle("Basic test")

上述结果:
enter image description here
这不是我想要的。
经过更多的实验,我发现改变这个:

^{pr2}$

为此:

self.setRect(0, 0, width, height)
self.setPos(50, 50)

成功了:
enter image description here
怎么会? 用setRect()设置矩形的位置与用setPos()显式设置位置有什么区别?在


Tags: textselfviewinitvaluesceneitemwidth
1条回答
网友
1楼 · 发布于 2024-09-28 04:24:27

不同之处在于,函数是根据不同的坐标系定义的。根据文档,setPos()定义了矩形在其父坐标系中的位置,而setRect()定义了矩形在其自身局部坐标系中的位置和大小。所以setPos()(x,y)和{}的{}没有相同的含义。在

对于setPos(50, 50),就是说矩形局部坐标系的原点位于QGraphicsScene(其父对象)坐标系中的(50, 50)位置。然后使用setRect(0, 0, width, height),就是说矩形位于它自己的坐标系中的原点(0,0)(实际上是场景坐标系中的(50, 50))。在

相关问题 更多 >

    热门问题