如何使覆盖的 QGraphicsTextItem 可编辑和可移动?

how to make an overriden QGraphicsTextItem editable & movable?

我正在使用 PyQt,我正在尝试重新实现 QGraphicsTextItem,但我似乎遗漏了一些东西。

我想让 NodeTag 项目的文本可编辑。我尝试设置诸如 Qt.TextEditorInteractionQGraphicsItem.ItemIsMovable 之类的标志,但这些标志似乎被忽略了...

这是一个最小的可重现示例:

import sys
from PyQt5.QtWidgets import QGraphicsScene, QGraphicsView, QMainWindow, QApplication, QGraphicsItem, QGraphicsTextItem

from PyQt5.QtCore import *
from PyQt5.QtGui import  QPen
    

class NodeTag(QGraphicsTextItem):
    def __init__(self,text):
        QGraphicsTextItem.__init__(self,text)
        self.text = text
        self.setPos(0,0)
        self.setTextInteractionFlags(Qt.TextEditorInteraction)
        # self.setFlag(QGraphicsItem.ItemIsFocusable, True)   # All these flags are ignored...
        # self.setFlag(QGraphicsItem.ItemIsSelectable, True)
        self.setFlag(QGraphicsItem.ItemIsMovable, True)

    def boundingRect(self):
        return QRectF(0,0,80,25)

    def paint(self,painter,option,widget):
        painter.setPen(QPen(Qt.blue, 2, Qt.SolidLine))
        painter.drawRect(self.boundingRect())
        painter.drawText(self.boundingRect(),self.text)
    
    def mousePressEvent(self, event):
        print("CLICK!")
        # self.setTextInteractionFlags(Qt.TextEditorInteraction) # make text editable on click
        # self.setFocus()


class GView(QGraphicsView):
    def __init__(self, parent, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.parent = parent
        self.setGeometry(100, 100, 700, 450)
        self.show()


class Scene(QGraphicsScene):
    def __init__(self, parent):
        super().__init__(parent)
        self.parent = parent
        tagItem = NodeTag("myText")   # create a NodeTag item
        self.addItem(tagItem)


class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()  # create default constructor for QWidget
        self.setGeometry(900, 70, 1000, 800)
        self.createGraphicView()
        self.show()

    def createGraphicView(self):
        self.scene = Scene(self)
        gView = GView(self)
        scene = Scene(gView)
        gView.setScene(scene)
        # Set the main window's central widget
        self.setCentralWidget(gView)

# Run program
if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = MainWindow()
    sys.exit(app.exec_())

如您所见,我已经尝试覆盖 mousePressEvent 并在那里设置标志,但到目前为止还没有成功。 任何帮助表示赞赏!

试一试:

...

        
class NodeTag(QGraphicsTextItem):
    def __init__(self, text, parent=None):
        super(NodeTag, self).__init__(parent)
        self.text = text
        self.setPlainText(text)

        self.setFlag(QGraphicsItem.ItemIsMovable)
        self.setFlag(QGraphicsItem.ItemIsSelectable)

    def focusOutEvent(self, event):
        self.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
        super(NodeTag, self).focusOutEvent(event)

    def mouseDoubleClickEvent(self, event):
        if self.textInteractionFlags() == QtCore.Qt.NoTextInteraction:
            self.setTextInteractionFlags(QtCore.Qt.TextEditorInteraction)
        super(NodeTag, self).mouseDoubleClickEvent(event)
       
    def paint(self,painter,option,widget):
        painter.setPen(QPen(Qt.blue, 2, Qt.SolidLine))
        painter.drawRect(self.boundingRect())
#        painter.drawText(self.boundingRect(),self.text)
        super().paint(painter, option, widget)
 ...

所有 QGraphicsItem subclasses 都有一个 paint 方法,所有绘制某些内容的项目都覆盖了该方法,以便它们实际上可以 paint他们自己。

该机制与标准QWidgets相同,其中有一个paintEvent(区别在于QGraphicsItem的paint接收一个已经实例化的QPainter),所以如果你想做进一步绘制其他比class已经提供的,必须调用基本实现。

考虑到绘画总是从下到上进行的,所以所有需要绘制的东西都必须在后面基础绘画之前完成] 调用 super().paint(),所有要绘制的东西 在默认绘制的 前面 必须放置在 之后

根据具体情况,重写可能需要调用默认的基本实现,这对 boundingRect 来说也很重要。当 QGraphicsTextItem 的内容改变时,它会自动调整自己的大小,所以你不应该总是 return 一个固定的 QRect。如果您需要最小尺寸,解决方案是将最小矩形 与默认 boundingRect() 函数提供的 合并。

然后,当项目获得焦点时,对 QGraphicsTextItem 进行编辑,但由于您还希望能够移动该项目,事情变得更加棘手,因为这两个操作都基于鼠标点击。如果您希望能够通过单击编辑文本,解决方案是在释放鼠标按钮时使项目可编辑和[=53] =] 没有被移动一定数量的像素(startDragDistance() 属性),否则项目被鼠标移动。这显然使 ItemIsMovable 标志变得无用,因为我们将在内部处理移动。

最后,由于提供了最小尺寸,我们还需要覆盖 shape() 方法以确保正确映射碰撞和点击,以及 return 包含整个的 QPainterPath边界矩形(对于正常的 QGraphicsItem,这应该是默认行为,但 QGraphicsRectItem 不会发生这种情况)。

下面是上述内容的完整实现:​​

class NodeTag(QGraphicsTextItem):
    def __init__(self, text):
        QGraphicsTextItem.__init__(self, text)
        self.startPos = None
        self.isMoving = False
        # the following is useless, not only because we are leaving the text
        # painting to the base implementation, but also because the text is 
        # already accessible using toPlainText() or toHtml()
        #self.text = text
        # this is unnecessary too as all new items always have a (0, 0) position
        #self.setPos(0, 0)

    def boundingRect(self):
        return super().boundingRect() | QRectF(0, 0, 80, 25)

    def paint(self, painter, option, widget):
        # draw the border *before* (as in "behind") the text
        painter.setPen(QPen(Qt.blue, 2, Qt.SolidLine))
        painter.drawRect(self.boundingRect())
        super().paint(painter, option, widget)

    def shape(self):
        shape = QPainterPath()
        shape.addRect(self.boundingRect())
        return shape

    def focusOutEvent(self, event):
        # this is required in order to allow movement using the mouse
        self.setTextInteractionFlags(Qt.NoTextInteraction)

    def mousePressEvent(self, event):
        if (event.button() == Qt.LeftButton and 
            self.textInteractionFlags() != Qt.TextEditorInteraction):
                self.startPos = event.pos()
        else:
            super().mousePressEvent(event)

    def mouseMoveEvent(self, event):
        if self.startPos:
            delta = event.pos() - self.startPos
            if (self.isMoving or 
                delta.manhattanLength() >= QApplication.startDragDistance()):
                    self.setPos(self.pos() + delta)
                    self.isMoving = True
                    return
        super().mouseMoveEvent(event)

    def mouseReleaseEvent(self, event):
        if (not self.isMoving and 
            self.textInteractionFlags() != Qt.TextEditorInteraction):
                self.setTextInteractionFlags(Qt.TextEditorInteraction)
                self.setFocus()
                # the following lines are used to correctly place the text 
                # cursor at the mouse cursor position
                cursorPos = self.document().documentLayout().hitTest(
                    event.pos(), Qt.FuzzyHit)
                textCursor = self.textCursor()
                textCursor.setPosition(cursorPos)
                self.setTextCursor(textCursor)

        super().mouseReleaseEvent(event)
        self.startPos = None
        self.isMoving = False

附带说明一下,请记住 QGraphicsTextItem 支持富文本格式,因此即使您想要对文本绘制过程进行更多控制,您也不应使用 QPainter.drawText(),因为您只会绘制 [=41] =]纯文本。事实上,QGraphicsTextItem 使用 drawContents() function of the underlying text document.

绘制其内容