Clear a QGraphicsScene from an event of one of the items - python

I have a QGraphicsScene with many QGraphicsItem. Some items have buttons that clear and repaint the scene.
The problem is that the clear() method deletes the QButton (and its
associated data structures) in the middle of a method call that uses
those very data structures. Then, immediately after clear() returns,
the calling method tries to access the now-deleted data (because it
wasn't expecting to be deleted in the middle of its routine), and bang
-- a crash. From here.
I found the solution for C ++ here, however I am using PySide and could not use the same solution for python.
Follow my code:
class GraphicsComponentButtonItem(QtGui.QGraphicsItem):
def __init__(self, x, y, update_out):
super(GraphicsComponentButtonItem, self).__init__()
self.x = x
self.y = y
self.update_out = update_out
self.setPos(x, y)
self.createButton()
self.proxy = QtGui.QGraphicsProxyWidget(self)
self.proxy.setWidget(self.button)
def boundingRect(self):
return QtCore.QRectF(self.x, self.y, self.button.width(), self.button.height())
def paint(self, painter, option, widget):
# Paint same stuffs
def createButton(self):
self.button = QtGui.QPushButton()
self.button.setText('Clear')
self.button.clicked.connect(self.action_press)
def action_press(self):
# Run some things
self.update_out()
class QGraphicsViewButtons(QtGui.QGraphicsView):
def __init__(self, scene, parent=None):
QtGui.QGraphicsView.__init__(self, parent)
self.scene = scene
# It's called outside
def updateScene(self):
self.scene.clear()
self.scene.addItem(GraphicsComponentButtonItem(0, 0, self.updateScene))
self.scene.addItem(GraphicsComponentButtonItem(0, 50, self.updateScene))
self.scene.addItem(GraphicsComponentButtonItem(0, 100, self.updateScene))

the conversion of the following C++ code:
QObject::connect(button, SIGNAL(clicked()), scene, SLOT(clear()), Qt::QueuedConnection);
to python is:
self.button.clicked.connect(self.scene().clear, QtCore.Qt.QueuedConnection)

Related

How to implement buttons in a delegate PyQt

I am making a program for translating text (see screenshot)
I have three classes
class for displaying a window that edits item :
class StyleDelegate(QStyledItemDelegate):
def __init__(self, parent=None):
super(StyleDelegate, self).__init__()
def createEditor(self, widget, style, index):
self.mainWidget = QWidget(widget)
self.line = QLineEdit() # line for input text
self.delButton= QPushButton('❌') # button for delete current item
self.trnButton = QPushButton('➕') # button for make translation text in another QListView
self.qhbLayout = QHBoxLayout()
self.qhbLayout.addWidget(self.line)
self.qhbLayout.addWidget(self.delButton)
self.qhbLayout.addWidget(self.trnButton)
self.mainWidget.setLayout(self.qhbLayout)
return self.mainWidget
# there is still a lot of code in this place
class for storing, adding, deleting and editing data:
class TranslateListModel(QAbstractListModel):
def __init__(self, parent=None):
super(TranslateListModel, self).__init__()
self.words = ['1', '2', '3', '4']
def removeItem(self, index):
self.beginRemoveRows(index, index.row(), index.row())
del self.words[index.row()]
self.endRemoveRows()
return True
# there is still a lot of code in this place
main class of the program:
class QTranslate(QtWidgets.QDialog, log.Ui_Dialog):
def __init__(self):
super().__init__()
self.originalModel = TranslateListModel()
self.translateModel = TranslateListModel()
self.styleDelegate = StyleDelegate()
self.originalLV.setModel(self.originalModel)
#QListView from Ui_Dialog
self.translateLV.setModel(self.translateModel)
#QListView from Ui_Dialog
self.originalLV.setItemDelegate(self.styleDelegate)
self.translateLV.setItemDelegate(self.styleDelegate)
# there is still a lot of code in this place
How to implement buttons to delete the current item and change the translation in another QListView using QStyledItemDelegate? I cannot access these buttons outside the StyleDelegate class to associate them with the methods of the TranslateListModel class.
A possible solution is to create signals for the delegate and connect them to the functions that will delete or add items, then emit those signals when the buttons are clicked:
class StyleDelegate(QStyledItemDelegate):
deleteRequested = QtCore.pyqtSignal(int)
translateRequested = QtCore.pyqtSignal(int)
def __init__(self, parent=None):
super(StyleDelegate, self).__init__()
def createEditor(self, widget, style, index):
# note: I removed the "self" references as they're unnecessary
mainWidget = QWidget(widget)
line = QLineEdit()
delButton= QPushButton('❌')
trnButton = QPushButton('➕')
qhbLayout = QHBoxLayout()
qhbLayout.addWidget(line)
qhbLayout.addWidget(delButton)
qhbLayout.addWidget(trnButton)
mainWidget.setLayout(qhbLayout)
delButton.clicked.connect(
lambda _, row=index.row(): self.deleteRequested.emit(row))
trnButton.clicked.connect(
lambda _, row=index.row(): self.translateRequested.emit(row))
return mainWidget
class QTranslate(QtWidgets.QDialog, log.Ui_Dialog):
def __init__(self):
# ...
self.originalLV.setItemDelegate(self.styleDelegate)
self.styleDelegate.deleteRequested.connect(self.deleteRow)
self.styleDelegate.translateRequested.connect(self.translateRow)
def deleteRow(self, row):
# ...
def translateRow(self, row):
# ...
Note that you should always use an unique delegate instance for each view, as explained in the documentation:
Warning: You should not share the same instance of a delegate between views. Doing so can cause incorrect or unintuitive editing behavior since each view connected to a given delegate may receive the closeEditor() signal, and attempt to access, modify or close an editor that has already been closed.

How to get mouse release coordinates in QGraphicsView

Hi I'm new to Qt and pyside. I'm trying to get the coordinates of mouse in a QGraphicsView instance. I tried to reimplement my mouseReleaseEvent but wondering how would I actually use this reimplemented function.
In MainWindow class:
self.tScn = QtGui.QGraphicsScene()
self.graphicsView_2 = QtGui.QGraphicsView(self.centralwidget, self.tScn)
In MainConsumer class(derived from MainWindow:
def pointSelection(self):
pos = self.tScn.mouseReleaseEvent(QMouseEvent)
print(pos)
def mouseReleaseEvent(self, QMouseEvent):
pos = QMouseEvent.lastScenePos()
print(pos)
return pos
python gives me this warning:
AttributeError: 'PySide.QtGui.QMouseEvent' object has no attribute 'lastScenePos'
I tried couple of different orders and structures but nothing worked and now I am really confused by the relationship between PySide.QtGui.QGraphicsScene.mouseReleaseEvent(event), PySide.QtGui.QGraphicsSceneMouseEvent.lastScenePos(), class PySide.QtGui.QGraphicsSceneMouseEvent([type=None]) and QtCore.QEvent.GraphicsSceneMouseRelease could somebody help me?
Thanks!
Create a class that inherits from QGraphicsScene and has a signal like this
class MyGraphicsScene(QtGui.QGraphicsScene):
signalMousePos = QtCore.pyqtSignal(QtCore.QPointF)
def __init__(self, parent):
super(MyGraphicsScene, self).__init__(parent)
and then override the mouseRelease event in this new class
def mouseReleaseEvent(QGraphicsSceneMouseEvent):
pos = QGrapihcsSceneMouseEvent.lastScenePos()
self.signalMousePos.emit(pos)
Then in your MainConsumer class replace
self.tScn = QtGui.QGraphicsScene()
with
self.tScn = MyQGraphicsScene()
self.tScn.signalMousePos.connect(self.pointSelection)
the pointSelection becomes
def pointSelection(self, pos)
#Whatever you want to do with the position coordinates
and mouseReleaseEvent in MainConsumer is no longer necessary

PyQt - Animations without redrawing everything?

So I'm trying to learn animations in PyQt and throughout all the examples I can find online, they all seem to use the self.update() or self.repaint() methods to increment the animations. This means basically the code has to erase then redraw the entire widget for every frame, even though much of what I intend to animate is static.
For example the code below, this generates a circular progress pie. The important bit is the paint() method under ProgressMeter (first class): for every frame in the animation this example paints the background, the actual progress pie, and the percentage indicator.
If I change the code to something like:
if self.angle > 120:
# do not draw background
then after 120 frames, the background does not get drawn anymore.
This seems terribly inefficient because (logically) the background should only be drawn once, no?
What would you recommend for animations like these?
Addendum: I have lurked a lot on this site to steal examples and code, but haven't posted for a long time. Please let me know about proper etiquette etc if I am not following it properly.
import sys
from PyQt4 import QtGui, QtCore
class ProgressMeter(QtGui.QGraphicsItem):
def __init__(self, parent):
super(ProgressMeter, self).__init__()
self.parent = parent
self.angle = 0
self.per = 0
def boundingRect(self):
return QtCore.QRectF(0, 0, self.parent.width(),
self.parent.height())
def increment(self):
self.angle += 1
self.per = int(self.angle / 3.6)
if self.angle > 360:
return False
else:
return True
def paint(self, painter, option, widget):
self.drawBackground(painter, widget)
self.drawMeter(painter, widget)
self.drawText(painter)
def drawBackground(self, painter, widget):
painter.setRenderHint(QtGui.QPainter.Antialiasing)
painter.setPen(QtCore.Qt.NoPen)
p1 = QtCore.QPointF(80, 80)
g = QtGui.QRadialGradient(p1 * 0.2, 80 * 1.1)
g.setColorAt(0.0, widget.palette().light().color())
g.setColorAt(1.0, widget.palette().dark().color())
painter.setBrush(g)
painter.drawEllipse(0, 0, 80, 80)
p2 = QtCore.QPointF(40, 40)
g = QtGui.QRadialGradient(p2, 70 * 1.3)
g.setColorAt(0.0, widget.palette().midlight().color())
g.setColorAt(1.0, widget.palette().dark().color())
painter.setBrush(g)
painter.drawEllipse(7.5, 7.5, 65, 65)
def drawMeter(self, painter, widget):
painter.setPen(QtCore.Qt.NoPen)
painter.setBrush(widget.palette().highlight().color())
painter.drawPie(7.5, 7.5, 65, 65, 0, -self.angle * 16)
def drawText(self, painter):
text = "%d%%" % self.per
font = painter.font()
font.setPixelSize(11)
painter.setFont(font)
brush = QtGui.QBrush(QtGui.QColor("#000000"))
pen = QtGui.QPen(brush, 1)
painter.setPen(pen)
# size = painter.fontMetrics().size(QtCore.Qt.TextSingleLine, text)
painter.drawText(0, 0, 80, 80,
QtCore.Qt.AlignCenter, text)
class MyView(QtGui.QGraphicsView):
def __init__(self):
super(MyView, self).__init__()
self.initView()
self.setupScene()
self.setupAnimation()
self.setGeometry(300, 150, 250, 250)
def initView(self):
self.setWindowTitle("Progress meter")
self.setRenderHint(QtGui.QPainter.Antialiasing)
policy = QtCore.Qt.ScrollBarAlwaysOff
self.setVerticalScrollBarPolicy(policy)
self.setHorizontalScrollBarPolicy(policy)
self.setBackgroundBrush(self.palette().window())
self.pm = ProgressMeter(self)
self.pm.setPos(55, 55)
def setupScene(self):
self.scene = QtGui.QGraphicsScene(self)
self.scene.setSceneRect(0, 0, 250, 250)
self.scene.addItem(self.pm)
self.setScene(self.scene)
def setupAnimation(self):
self.timer = QtCore.QTimeLine()
self.timer.setLoopCount(0)
self.timer.setFrameRange(0, 100)
self.animation = QtGui.QGraphicsItemAnimation()
self.animation.setItem(self.pm)
self.animation.setTimeLine(self.timer)
self.timer.frameChanged[int].connect(self.doStep)
self.timer.start()
def doStep(self, i):
if not self.pm.increment():
self.timer.stop()
self.pm.update()
app = QtGui.QApplication([])
view = MyView()
view.show()
sys.exit(app.exec_())
The Qt's documentation about QWidget repaint slot says:
Repaints the widget directly by calling paintEvent() immediately, unless updates are disabled or the widget is hidden.
We suggest only using repaint() if you need an immediate repaint, for example during animation. In almost all circumstances update() is better, as it permits Qt to optimize for speed and minimize flicker.
Warning: If you call repaint() in a function which may itself be called from paintEvent(), you may get infinite recursion. The update() function never causes recursion.
That should give you an answer about when to use or not repaint or update slots.
About making animations I'd suggest you also to take a look to the Qt4's animation framework or Qt5's animation framework, which is a really powerful way to animate widgets on Qt.

Update position of custom QGraphicsItem on connected item change

I have two subclassed QGraphicsRectItems that are supposed to be connected with a line that adjusts based on the position of the textboxes.
In the diagramscene example of the Qt docus the itemChanged method of a subclassed QGraphicsPolygonItem calls a updatePosition method of the connected arrow which calls setLine to update the arrow's position. In my case I cannot call setLine as I am subclassing QGraphicsItem instead of QGraphicsLineItem.
How should I implement updatePosition method in the Arrow class below to update the position of my QGraphicsItem? The following is a runnable example that shows what happens currently when the textboxes are clicked and moved.
import sys
from PyQt4.QtGui import *
from PyQt4.QtCore import *
class Arrow(QGraphicsItem):
def __init__(self, startItem, endItem, parent=None, scene=None):
super().__init__(parent, scene)
self.startItem = startItem
self.endItem = endItem
def boundingRect(self):
p1 = self.startItem.pos() + self.startItem.rect().center()
p3 = self.endItem.pos() + self.endItem.rect().center()
bounds = p3 - p1
size = QSizeF(abs(bounds.x()), abs(bounds.y()))
return QRectF(p1, size)
def paint(self, painter, option, widget=None):
p1 = self.startItem.pos() + self.startItem.rect().center()
p3 = self.endItem.pos() + self.endItem.rect().center()
pen = QPen()
pen.setWidth(1)
painter.setRenderHint(QPainter.Antialiasing)
if self.isSelected():
pen.setStyle(Qt.DashLine)
else:
pen.setStyle(Qt.SolidLine)
pen.setColor(Qt.black)
painter.setPen(pen)
painter.drawLine(QLineF(p1, p3))
painter.setBrush(Qt.NoBrush)
def updatePosition(self):
#Not sure what to do here...
class TextBox(QGraphicsRectItem):
def __init__(self, text, position, rect=QRectF(0, 0, 200, 100),
parent=None, scene=None):
super().__init__(rect, parent, scene)
self.setFlags(QGraphicsItem.ItemIsFocusable |
QGraphicsItem.ItemIsMovable |
QGraphicsItem.ItemIsSelectable)
self.text = QGraphicsTextItem(text, self)
self.setPos(position)
self.arrows = []
def paint(self, painter, option, widget=None):
painter.setPen(Qt.black)
painter.setRenderHint(QPainter.Antialiasing)
painter.setBrush(Qt.white)
painter.drawRect(self.rect())
def addArrow(self, arrow):
self.arrows.append(arrow)
def itemChange(self, change, value):
if change == QGraphicsItem.ItemPositionChange:
for arrow in self.arrows:
arrow.updatePosition()
return value
if __name__ == "__main__":
app = QApplication(sys.argv)
view = QGraphicsView()
scene = QGraphicsScene()
scene.setSceneRect(0, 0, 500, 1000)
view.setScene(scene)
textbox1 = TextBox("item 1", QPointF(50, 50), scene=scene)
textbox1.setZValue(1)
textbox2 = TextBox("item 2", QPointF(100, 500), scene=scene)
textbox2.setZValue(1)
arrow = Arrow(textbox1, textbox2, scene=scene)
arrow.setZValue(0)
textbox1.addArrow(arrow)
textbox2.addArrow(arrow)
view.show()
sys.exit(app.exec_())
The position of the item doesn't actually matter - it can remain at 0,0 - providing the bounding box is correct (which it will be according to your Arrow::boundingBox implementation). Hence, I think if you simply trigger a bounding box change, and a redraw in updatePosition, everything will work as you want.
Of course, if you care about the position of the arrow being at the head or tail of the line, you can move it in updatePosition, and adjust the bounding box / paint coordinates accordingly - but that's entirely up to you if that makes sense or not.

Qgraphicsview items not being placed where they should be

I recently created a program that will create QgraphicsEllipseItems whenever the mouse is clicked. That part works! However, it's not in the exact place where my cursor is. It seems to be slightly higher than where my mouse cursor is. I do have a QGraphicsRectItem created so maybe the two items are clashing with each other and moving off of one another? How can I get these circles to be placed on top of the rectangle item? Here's the code
class MyView(QtGui.QGraphicsView):
def __init__(self):
QtGui.QGraphicsView.__init__(self)
self.scene = QtGui.QGraphicsScene(self)
self.item = QtGui.QGraphicsRectItem(400, 400, 400, 400)
self.scene.addItem(self.item)
self.setScene(self.scene)
def paintMarkers(self):
self.cursor = QtGui.QCursor()
self.x = self.cursor.pos().x()
self.y = self.cursor.pos().y()
self.circleItem = QtGui.QGraphicsEllipseItem(self.x,self.y,10,10)
self.scene.addItem(self.circleItem)
self.circleItem.setPen(QtGui.QPen(QtCore.Qt.red, 1.5))
self.setScene(self.scene)
class Window(QtGui.QMainWindow):
def __init__(self):
#This initializes the main window or form
super(Window,self).__init__()
self.setGeometry(50,50,1000,1000)
self.setWindowTitle("Pre-Alignment system")
self.view = MyView()
self.setCentralWidget(self.view)
def mousePressEvent(self,QMouseEvent):
self.view.paintMarkers()
Much thanks!
There are two issues with the coordinates you are using to place the QGraphics...Items. The first is that the coordinates from QCursor are global screen coordinates, so you need to use self.mapFromGlobal() to convert them to coordinates relative to the QGraphicsView.
Secondly, you actually want the coordinates relative to the current QGraphicsScene, as this is where you are drawing the item. This is because the scene can be offset from the view (for example panning around a scene that is bigger than a view). To do this, you use self.mapToScene() on the coordinates relative to the QGraphicsView.
I would point out that typically you would draw something on the QGraphicsScene in response to some sort of mouse event in the QGraphicsView, which requires reimplementing things like QGraphicsView.mouseMoveEvent or QGraphicsView.mousePressEvent. These event handlers are passed a QEvent which contains the mouse coordinates relative to the view, and so you don't need to do the global coordinates transformation I mentioned in the first paragraph in these cases.
Update
I've just seen your other question, and now understand some of the issue a bit better. You shouldn't be overriding the mouse event in the main window. Instead override it in the view. For example:
class MyView(QtGui.QGraphicsView):
def __init__(self):
QtGui.QGraphicsView.__init__(self)
self.scene = QtGui.QGraphicsScene(self)
self.item = QtGui.QGraphicsRectItem(400, 400, 400, 400)
self.scene.addItem(self.item)
self.setScene(self.scene)
def paintMarkers(self, event):
# event position is in coordinates relative to the view
# so convert them to scene coordinates
p = self.mapToScene(event.x(), event.y())
self.circleItem = QtGui.QGraphicsEllipseItem(0,0,10,10)
self.circleItem.setPos(p.x()-self.circleItem.boundingRect().width()/2.0,
p.y()-self.circleItem.boundingRect().height()/2.0)
self.scene.addItem(self.circleItem)
self.circleItem.setPen(QtGui.QPen(QtCore.Qt.red, 1.5))
# self.setScene(self.scene) # <-- this line should not be needed here
# Note, I've renamed the second argument `event`. Otherwise you locally override the QMouseEvent class
def mousePressEvent(self, event):
self.paintMarkers(event)
# you may want to preserve the default mouse press behaviour,
# in which case call the following
return QGraphicsView.mousePressEvent(self, event)
Here we have not needed to use QWidget.mapFromGlobal() (what I covered in the first paragraph) because we use a mouse event from the QGraphicsView which returns coordinates relative to that widget only.
Update 2
Note: I've updated how the item is created/placed in the above code based on this answer.

Categories

Resources