Home > Blockchain >  Turn off pasting for QTextEdit object using PySide6
Turn off pasting for QTextEdit object using PySide6

Time:04-10

I'm trying to turn off pasting for a QtWidgets.QtextEdit object (PySide6), but am confused about whether it's off by default across platforms. E.g., I intuitively thought the following would work:

class MyEditor(QtWidgets.QTextEdit):
    def _setup_interface(self):
        self.canPaste(False)

but this results in an error since QtWidgets.QTextEdit.canPaste doesn't take an argument. Is there a way to explicitly turn off pasting, or do I need to trust it will be off by default?

CodePudding user response:

Names of functions that apply parameters or properties normally start with a set.
canPaste() just tells if the content of the clipboard can be used to paste in the text edit.

The solution is to override insertFromMimeData(), which is called every time there is an attempt to paste content, and just do nothing:

class NoPasteTextEdit(QtWidgets.QTextEdit):
    def insertFromMimeData(self, source):
        pass

Note that the context menu will still show the "Paste" action, so you should probably disable that, which can be achieved by overriding canInsertFromMimeData() and always returning False:

    def canInsertFromMimeData(self, source):
        return False

Be aware, though, that this will completely compromise the default behavior of internal editing through clipboard, including dragging a text selection to move it to another position.

A possible alternative is to override createMimeDataFromSelection(), get the QMimeData of the default implementation and add a custom format, in this way we can check in insertFromMimeData() and canInsertFromMimeData() whether the "pasted" data is generated internally or not and eventually accept or ignore it.

class NoPasteTextEdit(QtWidgets.QTextEdit):
    def canInsertFromMimeData(self, source):
        return source.hasFormat('InternalClipboard')

    def insertFromMimeData(self, source):
        if source.hasFormat('InternalClipboard'):
            super().insertFromMimeData(source)

    def createMimeDataFromSelection(self):
        # the mime object returned from the default implementation does
        # not allow to set further arbitrary data, so we just create a
        # standard QMimeData and fill it with the existing data
        mime = QtCore.QMimeData()
        src = super().createMimeDataFromSelection()
        for fmt in src.formats():
            mime.setData(fmt, src.data(fmt))
        mime.setData('InternalClipboard', QtCore.QByteArray())
        return mime
  • Related