pyqt5-QGraphicsView 的所有完成使用方法
时间: 2024-02-28 20:27:43 浏览: 169
QGraphicsView类的简单用法
QGraphicsView 是一个基于Qt的图形视图框架,可以方便的展现和编辑大量的2D图形元素。下面是QGraphicsView的一些常见用法:
1. 创建QGraphicsView对象
```python
from PyQt5.QtWidgets import QGraphicsView, QGraphicsScene
from PyQt5.QtCore import Qt
# 创建QGraphicsView对象
view = QGraphicsView()
# 创建QGraphicsScene对象
scene = QGraphicsScene()
# 将scene设置为view的场景
view.setScene(scene)
# 设置view的背景色
view.setBackgroundBrush(Qt.white)
```
2. 添加图形元素到场景中
```python
from PyQt5.QtGui import QPen, QColor, QBrush
from PyQt5.QtCore import QPointF, QRectF
# 创建QGraphicsRectItem对象
rect_item = QGraphicsRectItem(QRectF(0, 0, 100, 100))
# 设置该图形元素的画笔和画刷
pen = QPen(QColor(255, 0, 0))
brush = QBrush(QColor(0, 255, 0))
rect_item.setPen(pen)
rect_item.setBrush(brush)
# 将该图形元素添加到场景中
scene.addItem(rect_item)
```
3. 设置视图参数
```python
# 设置视图的中心点
view.setCenter(QPointF(0, 0))
# 设置视图的缩放比例
view.setTransform(QTransform.fromScale(2, 2))
```
4. 处理鼠标和键盘事件
```python
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QGraphicsView
class MyView(QGraphicsView):
def __init__(self, parent=None):
super(MyView, self).__init__(parent)
def mousePressEvent(self, event):
if event.button() == Qt.LeftButton:
print('left button pressed')
elif event.button() == Qt.RightButton:
print('right button pressed')
def keyPressEvent(self, event):
if event.key() == Qt.Key_Up:
print('up key pressed')
elif event.key() == Qt.Key_Down:
print('down key pressed')
```
以上是QGraphicsView的一些常见用法,希望对你有所帮助。
阅读全文