PyQt5开发画图工具
时间: 2023-10-05 08:15:00 浏览: 79
PyQt5是一个强大的GUI库,可以用它来开发各种桌面应用,包括画图工具。下面是一个简单的PyQt5画图工具的示例:
```python
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QAction, QFileDialog
from PyQt5.QtGui import QIcon, QPainter, QColor, QPen
from PyQt5.QtCore import Qt, QPoint
class DrawingApp(QMainWindow):
def __init__(self):
super().__init__()
self.setGeometry(100, 100, 800, 600)
self.setWindowTitle("Drawing App")
self.image = QImage(self.size(), QImage.Format_RGB32)
self.image.fill(Qt.white)
self.drawing = False
self.last_point = QPoint()
# Create the menu bar
menu_bar = self.menuBar()
file_menu = menu_bar.addMenu("File")
# Create the actions for the menu bar
save_action = QAction("Save", self)
save_action.setShortcut("Ctrl+S")
save_action.triggered.connect(self.save_image)
clear_action = QAction("Clear", self)
clear_action.setShortcut("Ctrl+C")
clear_action.triggered.connect(self.clear_image)
# Add the actions to the menu bar
file_menu.addAction(save_action)
file_menu.addAction(clear_action)
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.last_point = event.pos()
def mouseMoveEvent(self, event):
if event.buttons() == Qt.LeftButton and self.drawing:
painter = QPainter(self.image)
painter.setPen(QPen(Qt.black, 2, Qt.SolidLine))
painter.drawLine(self.last_point, event.pos())
self.last_point = event.pos()
self.update()
def mouseReleaseEvent(self, event):
if event.button() == Qt.LeftButton and self.drawing:
self.drawing = False
def save_image(self):
file_name, _ = QFileDialog.getSaveFileName(self, "Save Image", "", "PNG(*.png);;JPEG(*.jpg *.jpeg)")
if file_name:
self.image.save(file_name)
def clear_image(self):
self.image.fill(Qt.white)
self.update()
if __name__ == "__main__":
app = QApplication(sys.argv)
window = DrawingApp()
window.show()
app.exec_()
```
这个程序创建了一个带有菜单栏的窗口。通过菜单栏,用户可以保存或清除画布上的内容。用户可以使用鼠标在画布上绘制任意图形,程序使用QImage来保存绘制的内容。