# -*- coding: utf-8 -*-
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import QPainter, QPixmap
from PyQt5.QtCore import Qt, QPoint
from PyQt5 import QtWidgets, QtGui
class Winform(QWidget):
def __init__(self, parent=None):
super(Winform, self).__init__(parent)
#设置标题
self.setWindowTitle("绘图例子")
#实例化QPixmap类
self.pix = QPixmap()
#起点,终点
self.lastPoint = QPoint()
self.endPoint = QPoint()
#初始化
self.initUi()
def initUi(self):
# self.resize(600, 500) # 窗口大小设置为600*500,这样可以鼠标拖动缩放
self.setFixedSize(600, 500) # 固定窗口大小,不可缩放
# 画布大小为400*400,背景为白色
self.pix = QPixmap(500, 500)
self.pix.fill(Qt.white)
# 偏移量,保证鼠标的位置和画的线点是重合的
self.offset = QPoint(self.width() - self.pix.width(), self.height() - self.pix.height())
btn_clear = QPushButton(self)
btn_clear.setText("清空")
btn_clear.resize(80, 30)
btn_clear.move(10, 30)
btn_clear.clicked.connect(self.clear)
btn_save = QPushButton(self)
btn_save.setText("保存")
btn_save.resize(80, 30)
btn_save.move(10, 80)
btn_save.clicked.connect(self.save)
btn_open = QPushButton(self)
btn_open.setText("打开")
btn_open.resize(80, 30)
btn_open.move(10, 130)
btn_open.clicked.connect(self.open)
def clear(self):
self.pix.fill(Qt.white)
self.update()
def save(self):
self.pix.save("draw.jpg")
def open(self):
imgName, imgType = QFileDialog.getOpenFileName(self, "打开图片", "", "*.jpg;;*.png;;All Files(*)")
jpg = QPixmap(imgName).scaled(self.pix.width(), self.pix.height())
# self.label.setPixmap(jpg)
self.pix = jpg
def paintEvent(self, event):
pp = QPainter(self.pix)
# 根据鼠标指针前后两个位置绘制直线
pp.drawLine(self.lastPoint, self.endPoint)
# 让前一个坐标值等于后一个坐标值,
# 这样就能实现画出连续的线
self.lastPoint = self.endPoint
painter = QPainter(self)
#绘制画布到窗口指定位置处
painter.drawPixmap(100, 0, self.pix)
def mousePressEvent(self, event):
# 鼠标左键按下
if event.button() == Qt.LeftButton:
self.lastPoint = event.pos() - self.offset
# 上面这里减去一个偏移量,否则鼠标点的位置和线的位置不对齐
self.endPoint = self.lastPoint
print(self.endPoint)
def mouseMoveEvent(self, event):
# 鼠标左键按下的同时移动鼠标
if event.buttons() and Qt.LeftButton:
self.endPoint = event.pos() - self.offset
# 进行重新绘制
self.update()
def mouseReleaseEvent(self, event):
# 鼠标左键释放
if event.button() == Qt.LeftButton:
self.endPoint = event.pos() - self.offset
# 进行重新绘制
self.update()
if __name__ == "__main__":
app = QApplication(sys.argv)
form = Winform()
form.show()
sys.exit(app.exec_())
修改:20210804-17:15
def open(self):
imgName, imgType = QFileDialog.getOpenFileName(self, "打开图片", "", "*.jpg;;*.png;;All Files(*)")
jpg = QPixmap(imgName).scaled(self.pix.width(), self.pix.height())
# self.label.setPixmap(jpg)
if(jpg.isNull()!=True):
self.pix = jpg
加了一个打开图片是否为空的判断,否则,打开窗口打开后,不选择图片的话,就死了