PDA

View Full Version : How to add a pixmap drawn in QGraphicsItem to QGraphicsScene?



TheIndependentAquarius
17th April 2018, 05:24
How to add a pixmap drawn in QGraphicsItem to QGraphicsScene in the following example?



#!/usr/bin/env python

from PyQt5.QtCore import (QLineF, QPointF, QRectF, pyqtSignal)
from PyQt5.QtGui import (QIcon, QBrush, QColor, QPainter, QPixmap)
from PyQt5.QtWidgets import (QAction, QMainWindow, QApplication, QGraphicsObject, QGraphicsView, QGraphicsScene, QGraphicsItem,
QGridLayout, QVBoxLayout, QHBoxLayout,
QLabel, QLineEdit, QPushButton)

class TicTacToe(QGraphicsItem):
def __init__(self, helper):
super(TicTacToe, self).__init__()

self.mypixmap = QPixmap("exit.png")

self.painte = QPainter()

def paint(self, painter, option, widget):
self.painte.setOpacity(0.1)
self.painte.drawPixmap(0,0, 300, 300, self.mypixmap)


def boundingRect(self):
return QRectF(0,0,300,300)


class MyGraphicsView(QGraphicsView):
def __init__(self):
super(MyGraphicsView, self).__init__()
scene = QGraphicsScene(self)

self.tic_tac_toe = TicTacToe(self)

scene.addItem(self.tic_tac_toe)

scene.addPixmap(self.tic_tac_toe)

self.setScene(scene)

class Example(QMainWindow):
def __init__(self):
super(Example, self).__init__()

self.y = MyGraphicsView()
self.setCentralWidget(self.y)

if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
w = Example()
w.show()
sys.exit(app.exec_())

d_stranz
17th April 2018, 17:43
You're confused about ownership. You are creating your TicTacToe instance as a child of QGraphicsView; QGraphicsView instances don't own the objects displayed in them, the QGraphicsScene does.

Likewise, you should not be creating your QGraphicsScene as a child of QGraphicsView; if anything, it should be created in your QMainWindow (Example) __init__ constructor and owned by the Example instance.

So, you probably don't need a MyGraphicsView class at all - the out of the box QGraphicsView will do everything you want, I think. So get rid of that class completely.

In addition, QGraphicsPixmapItem does exactly what your TicTacToe class does. So either get rid of the TicTacToe class and use QGraphicsPixmapItem directly or derive your TicTacToe class from it if you need special code to handle mouse events, etc. If you do that, get rid of the paint() and boundingRect() methods from your TicTacToe class - the base class handles that.

In Example __init__ do the following:

- create the QGraphicsView (as that, not a derived class), owned by the Example instance as the central widget.
- create a QGraphicsScene as a child of the Example instance
- create a QGraphicsPixmapItem (or TicTacToe instance) using QGraphicsScene::addPixmap() (for a QGraphicsPixmapItem) or QGraphicsScene::addItem() (for a TicTacToe instance)
- call QGraphicsView::setScene() on your view instance.