我第一次尝试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")
上述结果:
这不是我想要的。
经过更多的实验,我发现改变这个:
为此:
self.setRect(0, 0, width, height)
self.setPos(50, 50)
不同之处在于,函数是根据不同的坐标系定义的。根据文档,}的{}没有相同的含义。在
setPos()
定义了矩形在其父坐标系中的位置,而setRect()
定义了矩形在其自身局部坐标系中的位置和大小。所以setPos()
的(x,y)
和{对于
setPos(50, 50)
,就是说矩形局部坐标系的原点位于QGraphicsScene
(其父对象)坐标系中的(50, 50)
位置。然后使用setRect(0, 0, width, height)
,就是说矩形位于它自己的坐标系中的原点(0,0)
(实际上是场景坐标系中的(50, 50)
)。在相关问题 更多 >
编程相关推荐