pyqt5中关于绘画功能的代码
时间: 2024-03-17 20:18:40 浏览: 67
以下是一个简单的PyQt5绘画应用程序的代码示例:
```python
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QGraphicsScene, QGraphicsView
from PyQt5.QtGui import QPainter, QPen
from PyQt5.QtCore import Qt
class MyCanvas(QGraphicsView):
def __init__(self):
super().__init__()
self.scene = QGraphicsScene(self)
self.setScene(self.scene)
self.pen = QPen(Qt.black, 2, Qt.SolidLine)
def mousePressEvent(self, event):
if event.button() == Qt.LeftButton:
self.last_point = event.pos()
def mouseMoveEvent(self, event):
if event.buttons() and Qt.LeftButton:
painter = QPainter()
painter.begin(self.scene)
painter.setPen(self.pen)
painter.drawLine(self.last_point, event.pos())
painter.end()
self.last_point = event.pos()
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.canvas = MyCanvas()
self.setCentralWidget(self.canvas)
self.setGeometry(100, 100, 640, 480)
self.setWindowTitle('PyQt5 Canvas')
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
mainWindow = MainWindow()
sys.exit(app.exec_())
```
这个应用程序创建了一个可以用鼠标绘画的画布。当鼠标左键按下时,记录下鼠标的位置。当鼠标移动时,用QPainter绘制一条线段,连接上一个点和当前点。在MainWindow中将MyCanvas设置为中央窗口,启动应用程序。
阅读全文