QPlainTextEdit::toPlainText() but include newline characters from word wrap
I have a QPlainTextEdit
that contains some text. Word wrap is enabled.
When I retrieve the text with toPlainText()
the resulting string does not contain the newline characters created from word wrap. This is because those newline characters weren't directly entered by the user.
I would like to retain those newline characters that word wrap created. How does one do this?
For example:
Add QPlainTextEdit
widget to the window and fill it with enough text for word wrap to create new lines.
Output that text to file:
QString myText = ui->plainTextEdit->toPlainText();
QFile outputFile("test.txt");
outputFile.open(QIODevice::WriteOnly);
outputFile.write(myText.toUtf8());
outputFile.close();
The resulting output is just 1 line.
How can I retain the newline characters word wrap simulates?
Solution 1:
I make offer use of QTextEdit
instead of QPlainTextEdit
, because its easy to access what you want (It does work) :
- Drag a
QTextEdit
control on widget - Select it, and change
lineWrapMode
option toFixedColumnWidth
(in properties section) - Then, set
lineWrapColumnOrWidth
option to (your arbitrary line length when wrapped e.g. 10) - Now fill
QTextEdit
, So you can see what you expected!
Now try this for get QTextEdit
data line by line ("textEdit"
is as QTextEdit
) :
// QTextEdit content
QString strLines = ui->textEdit->toPlainText();
// line count of QTextEdit
int lineCount = strLines.length() / ui->textEdit->lineWrapColumnOrWidth();
int lineLength = ui->textEdit->lineWrapColumnOrWidth();
for(int i = 0; i < lineCount; i++) {
QMessageBox::information(this, "", strLines.mid(i * lineLength, lineLength));
}
And for splitting real \n
You can try :
QString.split(QRegExp("[\r\n]"),QString::SkipEmptyParts);
This statement splits the string whenever any of the newline character.