我想通过在QGraphicsScene上使用鼠标事件来绘制矩形
class GraphicsItem(QGraphicsItem):
def __init__(self, parent):
super().__init__()
self.a = 0
self.b = 0
self.setFlag(QGraphicsItem.ItemIsFocusable)
self.setFocus()
self.screenSize = QDesktopWidget().screenGeometry(0)
self.screenHeight = self.screenSize.height()
self.screenWidth = self.screenSize.width()
def boundingRect(self):
self.posX = self.pos().x()
self.posY = self.pos().y()
return QRectF(0, 0, self.screenWidth, self.screenHeight)
def paint(self, painter, option, widget):
painter.setBrush(QBrush(Qt.red))
def mousePressEvent(self, event): pass
def mouseReleaseEvent(self, event): pass
def mouseMoveEvent(self, event): pass
class GraphicsScene(QGraphicsScene):
def __init__(self, parent):
super().__init__(parent=parent)
graphicsitem = GraphicsItem(self)
self.addItem(graphicsitem)
self.setBackgroundBrush(QColor(10, 155, 79))
self.screenSize = QDesktopWidget().screenGeometry(0)
self.screenHeight = self.screenSize.height()
self.screenWidth = self.screenSize.width()
class GraphicsView(QGraphicsView):
def __init__(self, parent):
super().__init__(parent=parent)
graphicsscene = GraphicsScene(self)
self.screenSize = QDesktopWidget().screenGeometry(0)
self.screenHeight = self.screenSize.height()
self.screenWidth = self.screenSize.width()
self.setGeometry(0, 0, self.screenWidth, self.screenHeight)
self.setScene(graphicsscene)
self.show()
class Widget(QWidget):
def __init__(self):
super().__init__()
graphicsview = GraphicsView(self)
self.screenSize = QDesktopWidget().screenGeometry(0)
self.screenHeight = self.screenSize.height()
self.screenWidth = self.screenSize.width()
self.initUI()
def initUI(self):
self.setWindowTitle("Graphics View")
self.setGeometry(0, 0, self.screenWidth, self.screenHeight)
self.show()
if __name__ == "__main__":
app = QApplication(sys.argv)
widget = Widget()
sys.exit(app.exec_())