Pyqt5로 캔버스 구현하기.
근데 QLabel 대신 QGraphicsView 사용.
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QWidget, QPushButton, QFileDialog, QLabel, QGraphicsView, QGraphicsScene
from PyQt5.QtWidgets import QHBoxLayout, QVBoxLayout
from PyQt5.QtGui import QPixmap, QImage, QPainter, QPen, QColor, QBrush
from PyQt5.QtCore import QPointF, QRectF, Qt
class GraphicView(QGraphicsView):
def __init__(self, parent):
super().__init__(parent)
self.scene = QGraphicsScene()
self.setScene(self.scene)
self.items = {}
self.items['rect'] = []
self.start = QPointF()
self.end = QPointF()
self.pen = QPen(QColor(0,0,0), 3)
self.setRenderHint(QPainter.HighQualityAntialiasing)
def moveEvent(self, e):
rect = QRectF(self.rect())
rect.adjust(0,0,-2,-2)
self.scene.setSceneRect(rect)
def mousePressEvent(self, e):
if e.button() == Qt.LeftButton:
self.start = e.pos()
self.end = e.pos()
rect = QRectF(self.start, self.end)
self.items['rect'].append(self.scene.addRect(rect, self.pen))
if e.button() == Qt.RightButton:
if self.scene.items():
self.scene.removeItem(self.items['rect'][-1])
del(self.items['rect'][-1])
def mouseMoveEvent(self, e):
if e.buttons() & Qt.LeftButton:
self.end = e.pos()
if self.scene.items():
self.scene.removeItem(self.items['rect'][-1])
del(self.items['rect'][-1])
rect = QRectF(self.start, self.end)
self.items['rect'].append(self.scene.addRect(rect, self.pen))
def mouseReleaseEvent(self, e):
if e.button() == Qt.LeftButton:
if self.scene.items():
self.scene.removeItem(self.items['rect'][-1])
del(self.items['rect'][-1])
rect = QRectF(self.start, self.end)
self.items['rect'].append(self.scene.addRect(rect, self.pen))
class Demo(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.view = GraphicView(self)
self.view.setFixedSize(640, 480)
main_layout = QHBoxLayout()
main_layout.addWidget(self.view)
widget = QWidget(parent=self)
widget.setLayout(main_layout)
self.setCentralWidget(widget)
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Demo()
sys.exit(app.exec_())
드래그하면 사각형이 그려진다.
우클릭하면 마지막에 그린 사각형을 삭제한다.
'Python' 카테고리의 다른 글
[PyQt5] QGraphicsView로 웹캠 영상 스트리밍하는 데모 만들기 (0) | 2023.03.16 |
---|---|
[Opencv] draw event (0) | 2023.02.22 |