PyQt5 在 QLabel 使用 QPainter 绘制矩形

一.基础使用

在QLabel 上绘制矩形,需要使用 paintEvent 并且重写 paintEvent 函数,因为Qpainter 在 QWidget 上不会报错,在其他地方直接使用就会报错.

from PyQt5.QtGui import QImage,QPixmap
import cv2
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
import sys


class MyLabel(QLabel):
    def __init__(self,text):
        super(MyLabel,self).__init__()
        self.x0 = 150
        self.y0 = 120
        self.x1 = 400
        self.y1 = 220
        self.x2 = 150
        self.y2 = 320
        self.x3 = 400
        self.y3 = 420
        self.lab1 = QLabel(self)
        self.lab2 = QLabel(self)
        self.lab1.setText(text)
        self.lab2.setText("操作区")
        self.lab1.setStyleSheet("QLabel{color:rgb(0,0,255);font-size:18px;font-family:Arial;background:transparent;}")
        self.lab2.setStyleSheet("QLabel{color:rgb(0,0,255);font-size:18px;font-family:Arial;background:transparent;}")
        self.lab1.setMaximumSize(100,200)
        self.lab2.setMaximumSize(100,200)
        self.lab1.move(150,120)
        self.lab2.move(150,320)

    #绘制事件
    def paintEvent(self, event):
        super().paintEvent(event)
        rect =QRect(self.x0, self.y0, abs(self.x1-self.x0), abs(self.y1-self.y0))
        painter = QPainter(self)
        painter.setPen(QPen(Qt.red,2,Qt.SolidLine))
        painter.drawRect(rect)
        rect1 = QRect(self.x2, self.y2, abs(self.x3 - self.x2), abs(self.y3 - self.y2))
        painter2 = QPainter(self)
        painter2.setPen(QPen(Qt.red, 2, Qt.SolidLine))
        painter2.drawRect(rect1)

class Example(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.resize(675, 500)
        self.move(100,50)
        self.setWindowTitle('在label中绘制矩形')
        self.lb = MyLabel("输入区") #重定义的label
        img = cv2.imread('a5.jpg')
        showImage = QImage(img.data, img.shape[1], img.shape[0],
                     QImage.Format_RGB888)  # 把读取到的图片数据变成QImage形式
        # 往显示视频的Label里 显示QImage
        self.lb.setPixmap(QPixmap.fromImage(showImage))
        #self.lb.setCursor(Qt.CrossCursor)
        self.horizontalLayout = QHBoxLayout(self)
        self.horizontalLayout.addWidget(self.lb)
        self.show()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    x = Example()
    sys.exit(app.exec_())

 上面的代码运行后就会在嵌套图片的QLabel中画了两个红色矩形.也可根据自己的需求是否要文字提示.

PyQt5 在 QLabel 使用 QPainter 绘制矩形_第1张图片

二.升级版一

from PyQt5.QtWidgets import QWidget, QApplication, QLabel
from PyQt5.QtCore import QRect, Qt
from PyQt5.QtGui import QImage, QPixmap, QPainter, QPen
import cv2
import sys

class MyLabel(QLabel):
    x0 = 0
    y0 = 0
    x1 = 0
    y1 = 0
    flag = False

    #鼠标点击事件
    def mousePressEvent(self,event):
        self.flag = True
        self.x0 = event.x()
        self.y0 = event.y()

    #鼠标释放事件
    def mouseReleaseEvent(self,event):
        self.flag = False

    #鼠标移动事件
    def mouseMoveEvent(self,event):
        if self.flag:
            self.x1 = event.x()
            self.y1 = event.y()
            self.update()

    #绘制事件
    def paintEvent(self, event):
        super().paintEvent(event)
        rect =QRect(self.x0, self.y0, abs(self.x1-self.x0), abs(self.y1-self.y0))
        painter = QPainter(self)
        painter.setPen(QPen(Qt.red,2,Qt.SolidLine))
        painter.drawRect(rect)

class Example(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.resize(675, 500)
        self.move(100,50)
        self.setWindowTitle('在label中绘制矩形')
        self.lb = MyLabel(self) #重定义的label
        img = cv2.imread('a5.jpg')
        showImage = QImage(img.data, img.shape[1], img.shape[0],
                     QImage.Format_RGB888)  # 把读取到的图片数据变成QImage形式
        # 往显示视频的Label里 显示QImage
        self.lb.setPixmap(QPixmap.fromImage(showImage))
        self.lb.setCursor(Qt.CrossCursor)#图片可以绘制
        self.show()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    x = Example()
    sys.exit(app.exec_())

代码运行后如下图所示,可以用鼠标绘制一个红色的方框. 

PyQt5 在 QLabel 使用 QPainter 绘制矩形_第2张图片

三.升级版二

直接上代码:

代码运行后如截图所示,这个升级版的亮点在于在制作界面Qlabel绘制方框时,可以根据具体界面的需求来绘制多个矩形方框.而不需要一直在MyLabel 类中设置方框(x,y)的位置,可以直接在调用函数中设置矩形的坐标直接绘制出矩形.这样方便制作界面,减少代码的重复率.

from PyQt5.QtGui import QImage,QPixmap
import cv2
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
import sys

class MyLabel(QLabel):
    def __init__(self):
        super().__init__()
        self.data = []

    def setxy(self,x1,y1,x2,y2,text):

        self.lab1 = QLabel(self)
        self.lab1.setText(text)
        self.lab1.setStyleSheet("QLabel{color:rgb(0,0,255);\
                                 font-size:18px;font-family:Arial;background:transparent;}")
        self.lab1.move(x1,y1)
        self.setGeometry(QRect(x1,y1,x2,y2))
        data = [x1,y1,x2,y2]
        self.data.append(data)

    #绘制表格
    def paintEvent(self,event):
        super().paintEvent(event)
        painter = QPainter()
        painter.begin(self)
        for data in self.data:
            rect = QRect(data[0], data[1], abs(data[2] - data[0]), abs(data[3] - data[1]))
            painter.setPen(QPen(Qt.red, 2, Qt.SolidLine))
            painter.drawRect(rect)
        painter.end()


class Example(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.resize(675, 500)
        self.move(100,50)
        self.setWindowTitle('在label中绘制矩形')
        self.lb = MyLabel() #重定义的label
        self.lb.setxy(150, 120, 250, 220, "输入区")
        #self.lb.setGeometry(QRect(150, 120, 250, 220))
        self.lb.setxy(300, 150, 400, 350, "绘图")
        #self.lb.setGeometry(QRect(300, 150, 400, 350))
        img = cv2.imread('a5.jpg')
        showImage = QImage(img.data, img.shape[1], img.shape[0],
                     QImage.Format_RGB888)  # 把读取到的图片数据变成QImage形式
        # 往显示视频的Label里 显示QImage
        self.lb.setPixmap(QPixmap.fromImage(showImage))
        #self.lb.setCursor(Qt.CrossCursor)
        self.horizontalLayout = QHBoxLayout(self)
        self.horizontalLayout.addWidget(self.lb)
        self.show()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    x = Example()
    sys.exit(app.exec_())

PyQt5 在 QLabel 使用 QPainter 绘制矩形_第3张图片

参考链接:https://blog.csdn.net/zzzzjh/article/details/82985209

              https://blog.csdn.net/pansaky/article/details/98958012

 

你可能感兴趣的:(pyqt5)