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:
    https://www.fileformat.info/info/unicode/char/00a0/index.htm

    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;
      txt.setPlainText(str);
      str = txt.toPlainText();
      qDebug() << "after" << str[0].unicode();
      return 0;
    }
    

  • Moderators

    @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';
                }
                else
                    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


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.