python PyQt5如何绘制矩形框?(画框/绘框)
生活随笔
收集整理的這篇文章主要介紹了
python PyQt5如何绘制矩形框?(画框/绘框)
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
參考代碼:
from PyQt5.QtWidgets import QWidget, QApplication, QLabel from PyQt5.QtCore import QRect, Qt from PyQt5.QtGui import QImage, QPixmap, QPainter, QPen, QGuiApplication import cv2 import sys class MyLabel(QLabel):x0 = 0y0 = 0x1 = 0y1 = 0flag = False#鼠標(biāo)點擊事件def mousePressEvent(self,event):self.flag = Trueself.x0 = event.x()self.y0 = event.y()#鼠標(biāo)釋放事件def mouseReleaseEvent(self,event):self.flag = False#鼠標(biāo)移動事件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, 300)self.setWindowTitle('在label中繪制矩形')self.lb = MyLabel(self) #重定義的labelself.lb.setGeometry(QRect(30, 30, 511, 541))img = cv2.imread('2.jpg')height, width, bytesPerComponent = img.shapebytesPerLine = 3 * widthcv2.cvtColor(img, cv2.COLOR_BGR2RGB, img)QImg = QImage(img.data, width, height, bytesPerLine,QImage.Format_RGB888)pixmap = QPixmap.fromImage(QImg)self.lb.setPixmap(pixmap)self.lb.setCursor(Qt.CrossCursor)self.show() if __name__ == '__main__':app = QApplication(sys.argv)x = Example()sys.exit(app.exec_())記得將名字為2.jpg的圖片跟程序放在同一目錄下
運行結(jié)果:
參考文章1:PyQt5中如何在lable中加載的圖片上繪制矩形框呢?
參考文章2:PyQt5 在label顯示的圖片中繪制矩形的方法
總結(jié)
以上是生活随笔為你收集整理的python PyQt5如何绘制矩形框?(画框/绘框)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python PyQt5 QColor(
- 下一篇: python PyQt5教程