Important: Please read the Qt Code of Conduct -

QTextEdit and Unicode char no-break space

  • When I fill a QTextEdit field with a string containing that character and then retrieve the content with toPlainText() that character is converted to a normal space (0x20)

    Is there any way to prevent this?

    No-break space is the following:

    minimal example to reproduce:

    #include <QtCore/qdebug.h>
    #include <QtWidgets/qapplication.h>
    #include <QtWidgets/qtextedit.h>
    int main(int argc, char **argv) {
      QApplication app(argc, argv);
      QString str(QChar(160));
      qDebug() << "before" << str[0].unicode();
      QTextEdit txt;
      str = txt.toPlainText();
      qDebug() << "after" << str[0].unicode();
      return 0;

  • Lifetime Qt Champion

    @Wurgl Try

    QString str = "\u00A0";

  • @jsulm, this is not the problem! The problem is documented in QTextEdit, where you can read:
    plainText : QString
    This property gets and sets the text editor's contents as plain text. Previous contents are removed and undo/redo history is reset when the property is set.
    If the text edit has another content type, it will not be replaced by plain text if you call toPlainText(). The only exception to this is the non-break space, nbsp;, that will be converted into standard space.

    I found a "hack" (or solution, you name it …) which looks like

            QTextDocument *doc = txt.document();
            QString str;
            for(int i = 0; i < doc->characterCount(); ++ i) {
                QChar c = doc->characterAt(i);
                if(c.unicode() == 0x2029) {
                    if(i < doc->characterCount() - 1)
                        str += '\n';
                    str += c;

    This seems to fix my problem, but I need more testing. I am sure there is still some hidden problem with some other unusual/strange/seldom used characters

  • @Wurgl I discovered that you can call


    This does not replace the non-break space chracter.

Log in to reply