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_())
网友评论