A
A
Artem2014-08-29 14:15:44
Qt
Artem, 2014-08-29 14:15:44

Why doesn't \n in QLabel wrap to a new line?

Here is the method that sets the text in the QLabel. Lines contain "\n". I replace it with "
" to move to a new line...
RegExp does not find "\n", but they are clearly there.

void setText(const std::string &text)
        {
            QString string(mTextCodec->toUnicode(text.c_str()));
            string.replace(QRegExp("\\n"), QString("<br\>"));
            mLabel.setText(string);
         }

And if I write like this, it works:
void setText(const std::string &text)
        {
            QString string("<i>I want to be able to switch it</i>\n<i>back if it doesn't fit.</i>");
            string.replace(QRegExp("\\n"), QString("<br\>"));
            mLabel.setText(string);
         }

I suspect that the problem may be with the encoding. what are the requirements or how can I convert everything to unicode so that I can normally replace \n with
?
Or maybe you don’t need to replace it at all, and you can use "\n" to force QLabel to do text wraps to a new line?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Artem, 2014-08-29
@Properrr

It was necessary to make 2nd screening:
1) Screening Sishnoe.
2) Escaping in RegExp.
Correct option:

string.replace(QRegExp("\\\\n"), QString("<br\>"));

J
jcmvbkbc, 2014-08-29
@jcmvbkbc

RegExp does not find "\n", but they are clearly there.
...
\n is two characters in source code only, in executable code it is one character (with code 10).
\\n is three characters in the source code and two -- \n in the executable.
The QLabel manual has this example:
QLabel *label = new QLabel(this);
 label->setFrameStyle(QFrame::Panel | QFrame::Sunken);
 label->setText("first line\nsecond line");
 label->setAlignment(Qt::AlignBottom | Qt::AlignRight);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question