I'd like to get raw text without style information when copying from a QPlainTextEdit. Currently when pasting into excel from a QPlainTextEdit there is style information included. I'm using PySide2.
Here's an image of excel illustrating the issue
I initially set the background color on column A to yellow and pasted on top of this column.
I've tried re-implementing createMimeDataFromSelection but if I create a new QMimeData, set the text and return it the program crashes with no error. After some further testing this method does work, and does not crash when using PyQt5 rather than PySide2. Maybe this is a bug with PySide2.
def createMimeDataFromSelection(self):
mime = QMimeData()
text = self.textCursor().selectedText()
mime.setText(text)
return mime #Crashes
If I use super() to get the parent's QMimeData and use setText() and setHtml() to override the text, when I copy I still get the original text with styling:
def createMimeDataFromSelection(self):
mime = super().createMimeDataFromSelection()
mime.clear()
mime.setData("text/plain", b"")
mime.setText(self.textCursor().selectedText())
mime.setHtml("")
return mime #Copied string still contains styling information
Here's a full example showing the standard a QPlainTextEdit, one that tries to replace the mime data provided by the parent class, and one that tries to create it's own mime data.
import sys
from PySide2.QtWidgets import QWidget, QPlainTextEdit, QApplication, QVBoxLayout
from PySide2.QtCore import QMimeData
class TextEditRemoveMime1(QPlainTextEdit):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def createMimeDataFromSelection(self):
mime = super().createMimeDataFromSelection()
mime.clear()
mime.setData("text/plain", b"")
mime.setText(self.textCursor().selectedText())
mime.setHtml("")
return mime
class TextEditRemoveMime2(QPlainTextEdit):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def createMimeDataFromSelection(self):
mime = QMimeData()
text = self.textCursor().selectedText()
mime.setText(text)
return mime
class Example(QWidget):
def __init__(self):
super().__init__()
vbox = QVBoxLayout()
# Has styling information
plainTextEdit = QPlainTextEdit(self)
vbox.addWidget(plainTextEdit)
# Still has styling information
plainTextEdit = TextEditRemoveMime1(self)
vbox.addWidget(plainTextEdit)
# Crashes in PySide2, but does remove styling and does not crash in PyQt5
plainTextEdit = TextEditRemoveMime2(self)
vbox.addWidget(plainTextEdit)
self.setLayout(vbox)
self.show()
if __name__ == "__main__":
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())