生成一段基于Qt设计绘画板的python代码
时间: 2023-12-20 19:03:30 浏览: 121
以下是一个基于Qt设计的绘画板的Python代码示例:
```python
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QAction, qApp
from PyQt5.QtGui import QIcon, QPainter, QPen
from PyQt5.QtCore import Qt
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("绘画板")
self.setGeometry(100, 100, 800, 600)
self.image = QImage(self.size(), QImage.Format_RGB32)
self.image.fill(Qt.white)
self.drawing = False
self.brushSize = 2
self.brushColor = Qt.black
self.lastPoint = None
self.createMenu()
def createMenu(self):
exitAction = QAction(QIcon("exit.png"), "退出", self)
exitAction.setShortcut("Ctrl+Q")
exitAction.setStatusTip("退出应用程序")
exitAction.triggered.connect(qApp.quit)
clearAction = QAction(QIcon("clear.png"), "清除", self)
clearAction.setShortcut("Ctrl+C")
clearAction.setStatusTip("清除画布")
clearAction.triggered.connect(self.clearImage)
menuBar = self.menuBar()
fileMenu = menuBar.addMenu("文件")
fileMenu.addAction(exitAction)
editMenu = menuBar.addMenu("编辑")
editMenu.addAction(clearAction)
def paintEvent(self, event):
painter = QPainter(self)
painter.drawImage(self.rect(), self.image, self.image.rect())
def mousePressEvent(self, event):
if event.button() == Qt.LeftButton:
self.drawing = True
self.lastPoint = event.pos()
def mouseMoveEvent(self, event):
if (event.buttons() & Qt.LeftButton) and self.drawing:
painter = QPainter(self.image)
painter.setPen(QPen(self.brushColor, self.brushSize, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin))
painter.drawLine(self.lastPoint, event.pos())
self.lastPoint = event.pos()
self.update()
def mouseReleaseEvent(self, event):
if event.button() == Qt.LeftButton and self.drawing:
self.drawing = False
painter = QPainter(self.image)
painter.setPen(QPen(self.brushColor, self.brushSize, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin))
painter.drawLine(self.lastPoint, event.pos())
self.lastPoint = None
self.update()
def clearImage(self):
self.image.fill(Qt.white)
self.update()
if __name__ == '__main__':
app = QApplication(sys.argv)
mainWindow = MainWindow()
mainWindow.show()
sys.exit(app.exec_())
```
这个绘画板基于Qt框架实现,使用了PyQt5库进行开发。在这个绘画板中,你可以使用鼠标进行自由绘画,并且支持清除画布和退出应用程序等功能。
阅读全文