计算qgraphicsrectitem项到qgraphicsview的坐标
时间: 2023-12-06 18:04:55 浏览: 104
要计算一个QGraphicsRectItem项(item)在QGraphicsView中的坐标,可以使用以下代码:
```python
# item是要计算的QGraphicsRectItem项
view = item.scene().views()[0] # 获取该项所在的场景中的视图
item_rect = item.mapToScene(item.rect()) # 获取该项在场景中的矩形
view_rect = view.viewport().rect() # 获取视图的矩形区域
view_center = view.mapToScene(view_rect.center()) # 获取视图中心点在场景中的坐标
item_center = item_rect.center() # 获取项的中心点在场景中的坐标
item_to_view = view_center - item_center # 计算项中心点与视图中心点的差值
```
这段代码首先获取该项所在的场景中的视图(假设该项只在一个视图中被显示)。然后,它使用`mapToScene()`函数将该项的矩形映射到场景坐标系中。接下来,它获取视图的矩形区域,并使用`mapToScene()`函数将视图中心点的坐标映射到场景坐标系中。最后,它计算项的中心点与视图中心点在场景坐标系中的差值,即项在视图中的偏移量。
请注意,这里假设该项只在一个视图中被显示,如果该项在多个视图中被显示,那么需要根据具体情况选择相应的视图进行计算。
相关问题
QGraphicsScene坐标转换为QGraphicsView坐标
要将QGraphicsScene中的坐标转换为QGraphicsView中的坐标,可以使用`QGraphicsView`类的`mapFromScene()`函数。这个函数将QGraphicsScene中的坐标映射到QGraphicsView中的坐标。
下面是一个示例代码,展示如何将QGraphicsScene中的坐标(100, 100)转换为QGraphicsView中的坐标:
```python
# 创建一个QGraphicsScene和QGraphicsView对象
scene = QGraphicsScene()
view = QGraphicsView(scene)
# 添加一个图形项到场景中
item = QGraphicsRectItem(0, 0, 100, 100)
scene.addItem(item)
# 将QGraphicsScene中的坐标(100, 100)转换为QGraphicsView中的坐标
scene_pos = QPointF(100, 100)
view_pos = view.mapFromScene(scene_pos)
print(view_pos)
```
这样,你就可以通过`view_pos`获取到在QGraphicsView中对应的坐标。
设置QGraphicsItem在QGraphicsView的坐标
要将QGraphicsItem放置在QGraphicsView中的特定坐标上,可以使用以下步骤:
1. 创建一个QGraphicsView对象和一个QGraphicsScene对象:
```python
view = QGraphicsView()
scene = QGraphicsScene()
view.setScene(scene)
```
2. 创建一个QGraphicsItem对象(例如QGraphicsRectItem)并设置其位置和尺寸:
```python
item = QGraphicsRectItem(0, 0, 100, 100) # 参数分别为x、、width、height
```
3. 将QGraphicsItem添加到QGraphicsScene中:
```python
scene.addItem(item)
```
4. 设置QGraphicsView的坐标系统为Scene坐标系:
```python
view.setRenderHint(QPainter.Antialiasing)
view.setRenderHint(QPainter.TextAntialiasing)
view.setRenderHint(QPainter.SmoothPixmapTransform)
view.setRenderHint(QPainter.HighQualityAntialiasing)
view.setRenderHint(QPainter.NonCosmeticDefaultPen)
view.setDragMode(QGraphicsView.ScrollHandDrag)
view.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
view.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
view.setScene(scene)
```
5. 设置QGraphicsView的大小和位置:
```python
view.setGeometry(x, y, width, height) # 参数分别为x、y、width、height
```
这样,QGraphicsItem将会在指定坐标上显示在QGraphicsView中。记得在设置坐标之前,确保已经设置好了QGraphicsView的大小和位置。
阅读全文
相关推荐
















