项目实战:实现绘图应用 的案例
需要解决3个核心内容
1.如何绘图
在paintEvent方法中绘图,通过调用update方法出发painEvent的条用
2.在哪里绘图
在白色北京的QPixmap对象中绘图
3.如何通过移动鼠标进行绘图
鼠标拥有3个事件:
(1) 鼠标按下 mousePressEvent
(2) 鼠标移动 mouseMoveEvent
(3) 鼠标抬起 mouseReleaseEvent
'''
项目实战:实现绘图应用 的案例
需要解决3个核心内容
1.如何绘图
在paintEvent方法中绘图,通过调用update方法出发painEvent的条用
2.在哪里绘图
在白色北京的QPixmap对象中绘图
3.如何通过移动鼠标进行绘图
鼠标拥有3个事件:
(1) 鼠标按下 mousePressEvent
(2) 鼠标移动 mouseMoveEvent
(3) 鼠标抬起 mouseReleaseEvent
'''
import sys
from PyQt5.QtCore import Qt, QPoint
from PyQt5.QtGui import QIcon, QPixmap, QPainter
from PyQt5.QtWidgets import QWidget, QLineEdit, QPushButton, QGridLayout, QDialog, QApplication, QMainWindow, \
QVBoxLayout
class DrawingDemo(QWidget):
def __init__(self,parent=None):
super(DrawingDemo,self).__init__(parent)
# 设置窗口标题
self.setWindowTitle('绘图应用 的演示')
self.pix = QPixmap()
self.lastPoint = QPoint()
self.endPoint = QPoint()
self.initUI()
def initUI(self):
# 设置定位和左上角坐标
self.resize(600,600)
# 画布大小为400*400 , 背景为白色
self.pix = QPixmap(600,600)
self.pix.fill(Qt.white)
def paintEvent(self, event):
pp = QPainter(self.pix)
# 根据鼠标指针前后两个位置绘制直线
pp.drawLine(self.lastPoint,self.endPoint)
# 让前一个坐标等于后一个坐标值
# 这样就能实现出连续的线
self.lastPoint = self.endPoint
painter = QPainter(self)
painter.drawPixmap(0,0,self.pix)
def mousePressEvent(self, event):
if event.button() == Qt.LeftButton:
self.lastPoint = event.pos()
def mouseMoveEvent(self, event):
if event.buttons() and Qt.LeftButton:
self.endPoint = event.pos()
self.update()
def mouseReleaseEvent(self, event):
if event.button() == Qt.LeftButton:
self.endPoint = event.pos()
if __name__ == '__main__':
app = QApplication(sys.argv)
# 设置应用图标
app.setWindowIcon(QIcon('../web.ico'))
w = DrawingDemo()
w.show()
sys.exit(app.exec_())