首页 > 解决方案 > PyQt5 QTextEdit changes color when copy / pasting into it

问题描述

In my application, I have a QTextEdit. It works just fine when I write normally into it but when I copy / paste text from my IDE ( as an example - in my case, pycharm in dark mode ) into it, the QTextEdit also takes the color and background of the text.

This is the normal appearance :

normal appearance

This is what happens when I copy paste from my IDE :

enter image description here

When the color is changed, the next writing inputs will keep the same colors until the next copy / paste.

How can I avoid the QTextEdit having anything else than the default colors ( black text, white background ) ?

标签: python-3.xpyqt5

解决方案


QTextEdit has the acceptRichText property.

Just set it to False.


QTextEdit allows using rich text content, and if the source you're getting the text from supports rich text for the clipboard, you'll get that.
To avoid this behavior, you can subclass QTextEdit and override insertFromMimeData(mimeData)


class TextEdit(QtWidgets.QTextEdit):
    def insertFromMimeData(self, source):
        newData = QtCore.QMimeData()
        for format in source.formats():
            if format == 'text/plain':
                newData.setData(format, source.data(format))
        super().insertFromMimeData(newData)

推荐阅读