PyQt5 - Program crashes when editable QGraphicsTextItem is clicked with right mouse button

Viewed 144

I've made a program with PyQt5. I have a main window containing a QGraphicsScene within a QGraphicsView. I have an editable QGraphicsTextItem in the scene as follows.

import sys
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QMainWindow, QGraphicsView, QGraphicsScene, QHBoxLayout, QWidget, QApplication, QGraphicsTextItem

class Window(QMainWindow):

    def __init__(self):
        super(Window, self).__init__()

        self.scene = QGraphicsScene()
        self.graphicsview = QGraphicsView(self.scene)
        self.layout = QHBoxLayout()
        self.layout.addWidget(self.graphicsview)
        self.setCentralWidget(QWidget())
        self.centralWidget().setLayout(self.layout)
        self.resize(500, 500)
        self.graphicsview.show()
        self.show()

        textitem = QGraphicsTextItem("Test")
        textitem.setTextInteractionFlags(Qt.TextEditorInteraction)
        self.scene.addItem((textitem))



def main():

    app = QApplication(sys.argv)
    window = Window()
    sys.exit(app.exec())


main()

The problem is that the program crashes if the right mouse button is clicked within the textitem's area in the scene. The textitem and the text editor work fine as long as the right mouse button is not being clicked upon the item.

If I don't set the TextEditorInteraction, the right mouse button don't cause any problems.

I've tried using setAcceptedMouseButtons() -method to only allow left mouse button clicks on the item, but it has not had any effect. Not sure if I got the syntax right though.

I've tried to find a fix to this problem for quite a while now, but nothing has worked so far.

1 Answers

Same problem on PyQt 5.15.2, Win10 and PyCharm IDE setup. Running on command prompt does not produce any traceback error either. Event viewer gave some more details:

"Faulting module name: Qt5Widgets.dll, version: 5.15.2.0, time stamp: 0x5fa4de1c Exception code: 0xc0000005".

It seems to be the code of a memory access issue but I couldnt find how it is anyway related to our problem here.

 I had the following fix:

  • Subclass a TextItem that handles the mouse press events.
  • When right click change the editable text into non-editable mode.
  • When left click change it back to editable mode.
class TextItem(QGraphicsTextItem):
    def __init__(self,text):
        super().__init__(text)

    def mousePressEvent(self, event):
        if event.button() == Qt.LeftButton:
            self.setTextInteractionFlags(Qt.TextEditable)
            print("Left Button Clicked")
        elif event.button() == Qt.RightButton:
            self.setTextInteractionFlags(Qt.NoTextInteraction)
            print("Right Button Clicked")
Related