I’m currently making a notepad and I’ve found a problem.
I want to save a file formatting the text so with different fonts, point sizes and colors in a .rtf file, but it just saves without formatting it so without any color or different fonts.
Here is the code I put to save a file:
void MainWindow::on_saveas_clicked()
{
QTextEdit *edit = getTabTextEdit();
QString fileName;
fileName = QFileDialog::getSaveFileName(this, tr("Save a file"), "New Document", tr("Rich Text Format(*.rtf);; All Files (*)"));
QFile file(fileName);
if(ui->tabWidget->currentWidget() == ui->tab_1)
{
if(file.open(QIODevice::WriteOnly | QFile::Text))
{
ui->tabWidget->setTabText(ui->tabWidget->currentIndex(), file.fileName());
QTextStream out (&file);
QString text = ui->edit->toPlainText();
out << text;
file.close();
ui->edit->setFocus();
}
}
else
{
if(file.open(QIODevice::WriteOnly | QFile::Text))
{
ui->tabWidget->setTabText(ui->tabWidget->currentIndex(), file.fileName());
QTextStream out (&file);
QString text = edit->toPlainText();
out << text;
file.close();
edit->setFocus();
}
}
}
Is there a way to save a file formatting the text of the QTextEdit?
2
I guess that Qt does not support RTF format, which is a proprietary format by MS, see https://en.wikipedia.org/wiki/Rich_Text_Format. So it does no make sense to save it with RTF extension. Nevermind.
Qt however does support formatting via HTML tags (at least some subset of HTML, see https://doc.qt.io/qt-5/richtext-html-subset.html). So you can save your file as HTML and load it the same way. Just use QTextEdit::toHtml()
and QTextEdit::setHtml()
, see https://doc.qt.io/qt-5/qtextedit.html#html-prop. In other words, do not use toPlainText()
if you want formatted text. Plain text is called plain because it does not contain any formatting.
0
Try
file.write(edit->toPLainText().toLocal8Bit());
Because, QTextStream writes the text with format information’s.
2