[Qt-interest] Howto make QGraphicsTextItem draggable?
John Posner
jjposner at optimum.net
Thu Dec 31 22:55:55 CET 2009
Wilhelm wrote:
> Hi,
>
> I want to make a QGraphicsTextItem drag and droppable AND still moveable
> like the normal behaviour if I set QGraphicsItem::ItemIsMovable (see
> below). Additionally I want to have the original text drawn while the
> drag is active, so I tried to set the drag pixmap. But if I try to use a
> painter to draw the item onto a pixmap, the application crashes with a
> segfault (if you uncomment the commented codelines below).
> What am I doing wrong here?
>
I can't comment on what your code does wrong, but here is some PyQt4
code (Python) that has a dragged text item leave behind an italicized
"ghost" of itself. The ghost disappears when you drop the text item.
#-------------------------
from PyQt4.QtCore import *
from PyQt4.QtGui import *
TEXT = "hello world"
class GhostText(QGraphicsTextItem):
def __init__(self, txt):
super(GhostText, self).__init__(txt)
self.setDefaultTextColor(Qt.red)
self.setFlags(QGraphicsItem.ItemIsMovable)
self.ghost = None
def mousePressEvent(self, evt):
"""create ghost text item at current position"""
self.ghost = QGraphicsTextItem()
self.ghost.setHtml("<i>%s</i>" % TEXT)
scene.addItem(self.ghost)
self.ghost.moveBy(self.x(), self.y())
super(GhostText, self).mousePressEvent(evt)
def mouseReleaseEvent(self, evt):
"""remove ghost text item"""
scene.removeItem(self.ghost)
self.ghost.deleteLater()
super(GhostText, self).mouseReleaseEvent(evt)
# main program
app = QApplication([])
win = QMainWindow()
win.resize(500+25, 300+25)
# create a view, scene, and text item
view = QGraphicsView()
win.setCentralWidget(view)
scene = QGraphicsScene()
view.setScene(scene)
view.setSceneRect(0, 0, 500, 300)
scene.addItem(GhostText(TEXT))
# go
win.show()
app.exec_()
#-------------------------
HTH,
John
More information about the Qt-interest-old
mailing list