So, I'm making a text editor in Qt. And It does mostly very basic functions. New file, save, open, cut, copy, paste, bold, underline, italic, undo, and redo. But, when I bold, italicize, or underline text and then open the text file again It opens as plain text. As in if you open a file, bold some text, save it and then open it again it will be in plain text not bolded or anything. I have tried reading about how to make it work the way I want, but with no luck. My program can even create/open rich text files, but it works the exact same way. I understand that the way I have written the code makes it work the way it does. I just don't know how to "fix" it.

Here are the blocks of code I have written that save and open files using the QFileDialog:

void WordWriteMain::on_actionOpen_File_triggered()
{
    QString fileName = QFileDialog::getOpenFileName(this,"Open a file","","Text (*.txt);;Rich Text (*.rtf)");
    QFile file(fileName);
    if(file.open(QIODevice::ReadOnly|QIODevice::Text)){
    ui->textBox->setText((file.readAll()));
    }
}

void WordWriteMain::on_actionSave_triggered()
{
    QString fileName = QFileDialog::getSaveFileName(this,"Open a file","","Text (*.txt);;Rich Text (*.rtf)");
    QFile file(fileName);
    if(file.open(QIODevice::WriteOnly|QIODevice::Text)){
        file.write(ui->textBox->toPlainText().toUtf8());
    }
}

Is what I'm trying to do even possible using QFileDialog? And like I said I understand the line file.write(ui->textBox->toPlainText().Utf8()); converts all of the text into plain text, but I don't know how to make the save slot work without doing it that way. As always thank you so much for dedicating your time to help me and for reading my question. If there is any more information needed I would be more than happy to provide it. EDIT: Also, I would like in the future to be able to add paragraph aligning so should I make my text editor strictly rich text?

有帮助吗?

解决方案

Use toHtml() instead of toPlainText(). When setting use setHtml() instead setText()

Also use toAscii() instead of toUtf8() to do not loose user's language code page.

See: http://doc.qt.io/archives/qt-4.7/qtextedit.html

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top