用pycharm编写简单的鼠标绘图软件
时间: 2024-02-24 09:55:49 浏览: 68
好的,下面是一个简单的鼠标绘图软件的代码,基于PyQt5库实现:
```python
import sys
from PyQt5.QtGui import QPainter, QColor, QPen
from PyQt5.QtWidgets import QApplication, QMainWindow, QWidget
from PyQt5.QtCore import Qt, QPoint
class MyCanvas(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.setGeometry(100, 100, 800, 600)
self.setWindowTitle('My Canvas')
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 = QPoint()
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() and 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:
self.drawing = False
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.canvas = MyCanvas()
self.setCentralWidget(self.canvas)
self.initUI()
def initUI(self):
self.setGeometry(100, 100, 800, 600)
self.setWindowTitle('My Paint')
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
window = MainWindow()
sys.exit(app.exec_())
```
这个程序使用了PyQt5库,创建了一个窗口并在其中添加了一个自定义的QWidget类MyCanvas,用来绘制图形。在MyCanvas类中实现了绘制图形的功能,包括鼠标事件的处理和绘图操作的实现。在MainWindow类中将MyCanvas类添加到窗口中,并显示窗口。
阅读全文