Save a .rtf file formatting the text in a QTextEdit
-
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_save_clicked() { QTextEdit *edit = getTabTextEdit(); QString fileName; if (currentFile.isEmpty()) { fileName = QFileDialog::getSaveFileName(this, tr("Save a file"), "New Document", tr("Text File (*.txt);; RichTextFormat File (*.rtf);; All Files (*)")); currentFile = fileName; } else { fileName = currentFile; } 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); out << ui->edit->toPlainText(); file.close(); ui->edit->setFocus(); } } else { if(file.open(QIODevice::WriteOnly | QFile::Text)) { ui->tabWidget->setTabText(ui->tabWidget->currentIndex(), file.fileName()); QTextStream out (&file); out << edit->toPlainText(); file.close(); edit->setFocus(); } } }
Is there a way to save a file formatting the text of the QTextEdit?
-
@HenkCoder There is, to some extent. Please see overview under the link below.
-
As already told on so you use toPlaintText() and wonder why the formatting is not saved... isn't the function name meaningful enough?
-
@Christian-Ehrlicher alright, but is there a way to get the formatted text?
-
@HenkCoder I suggest you read that again maybe?
As documentation states, rich text formatting in Qt is done via HTML subset. So, in case of QTextEdit, you will look at toHtml() method to obtain formatted text.
RTF is closed format, owned by Microsoft, however its specification is available - since Qt lacks direct support my approach would be to implement a model that converts Qt Rich Text to RTF and vice versa https://docs.microsoft.com/en-us/previous-versions/office/developer/office2000/aa140280(v=office.10)?redirectedfrom=MSDN