美文网首页
pyqt 图像画线

pyqt 图像画线

作者: 你好_3821 | 来源:发表于2023-09-24 13:32 被阅读0次
from PyQt5.QtWidgets import QApplication, QLabel, QMainWindow, QVBoxLayout, QWidget
from PyQt5.QtGui import QPainter, QPen, QPixmap
from PyQt5.QtCore import Qt, QRect


class ImageWidget(QLabel):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setPixmap(QPixmap(r"D:\merge.png"))  # 设置你的图像路径
        self.rects = []
        self.current_rect = QRect()

    def mousePressEvent(self, event):
        self.current_rect.setTopLeft(event.pos())
        self.current_rect.setBottomRight(event.pos())
        self.update()

    def mouseMoveEvent(self, event):
        self.current_rect.setBottomRight(event.pos())
        self.update()

    def mouseReleaseEvent(self, event):
        self.current_rect.setBottomRight(event.pos())
        self.rects.append(QRect(self.current_rect))  # 添加当前矩形到列表
        self.update()

    def paintEvent(self, event):
        super().paintEvent(event)
        painter = QPainter(self)
        painter.setPen(QPen(Qt.red, 2, Qt.SolidLine))
        for rect in self.rects:  # 遍历列表并画出所有的矩形
            painter.drawRect(rect)
        painter.drawRect(self.current_rect)


class MainWindow(QMainWindow):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowTitle("Draw Rectangle on Image")
        self.setGeometry(100, 100, 600, 400)

        self.image_widget = ImageWidget(self)

        layout = QVBoxLayout()
        layout.addWidget(self.image_widget)

        main_widget = QWidget(self)
        main_widget.setLayout(layout)

        self.setCentralWidget(main_widget)


if __name__ == "__main__":
    import sys

    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())

相关文章

网友评论

      本文标题:pyqt 图像画线

      本文链接:https://www.haomeiwen.com/subject/flgfbdtx.html