使用qgraphicsview创建一个简单画板
时间: 2024-02-21 15:27:48 浏览: 67
以下是一个简单的画板的代码示例,使用了QGraphicsView和QGraphicsScene实现:
```python
from PyQt5.QtWidgets import QApplication, QGraphicsView, QGraphicsScene
from PyQt5.QtGui import QPen, QColor
from PyQt5.QtCore import Qt
class PaintView(QGraphicsView):
def __init__(self, parent=None):
super().__init__(parent)
self.scene = QGraphicsScene(self)
self.setScene(self.scene)
self.pen = QPen(QColor(0, 0, 0), 2)
def mousePressEvent(self, event):
if event.button() == Qt.LeftButton:
self.last_point = event.pos()
def mouseMoveEvent(self, event):
if event.buttons() == Qt.LeftButton:
new_point = event.pos()
self.scene.addLine(self.last_point.x(), self.last_point.y(),
new_point.x(), new_point.y(), self.pen)
self.last_point = new_point
if __name__ == '__main__':
app = QApplication([])
view = PaintView()
view.show()
app.exec_()
```
运行该代码会打开一个空白的窗口,当鼠标左键被按下并移动时,会在窗口中绘制出一条直线。可以通过更改pen属性来改变绘制线条的颜色和粗细。
阅读全文