I am trying to draw a rectangle in QGraphicscene to select the part of the QGraphicsitem.
I have tried the following code but is not working as i expected.It is not showing any error and expected result too
from PyQt5.QtCore import (QByteArray, QDataStream, QIODevice, QMimeData, QPointF, QPoint, Qt, QEvent, QCoreApplication,QRect,QSize,QSortFilterProxyModel,QRegExp)
from PyQt5.QtGui import QColor, QDrag, QPainter, QPixmap, QBrush,QCursor,QPolygon, QLinearGradient, QIcon, QPen, QPainterPath, QTransform,QStandardItem,QStandardItemModel
from PyQt5.QtWidgets import QGraphicsScene, QMainWindow, QAction, QGraphicsView, QGraphicsItem
import sys
from PyQt5 import QtWidgets, QtCore
from PyQt5.QtGui import QPainter
class MyWidget(QGraphicsView):
def __init__(self):
super().__init__()
self.scene=QGraphicsScene()
self.setSceneRect(0,0,600,600)
self.setScene(self.scene)
self.scene.setItemIndexMethod(QGraphicsScene.NoIndex)
self.scene.setBackgroundBrush(QBrush(Qt.black))
self.begin = QtCore.QPoint()
self.end = QtCore.QPoint()
self.targetForLine=QRect()
self.show()
def mousePressEvent(self, event):
self.target = self.TargPosForLine((event.pos()), "ForRect")#Geometry of rectangle
qp=QPainter()
qp.setPen(QColor(Qt.red))
br = QBrush(QColor(Qt.red))
qp.setBrush(br)
qp.drawRect(QRect(self.target))
# qp.drawRect(10,10,100,100)
self.update()
def TargPosForLine(self, position, mode):
self.clicked_column = int((position.y() // 16)) * 16
self.clicked_row = int((position.x() // 16)) * 16
if self.clicked_column < 0:
self.clicked_column = 0
if self.clicked_row < 0:
self.clicked_row = 0
if (mode == "ForRect"):
return QRect(self.clicked_row, self.clicked_column, 16, 16)
def mouseMoveEvent(self, event):
self.end = event.pos()
self.update()
#
# def mouseReleaseEvent(self, event):
# self.scene.removeItem(qp)
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
window = MyWidget()
window.show()
app.aboutToQuit.connect(app.deleteLater)
sys.exit(app.exec_())