Qt Pig Latin Translator: Part 2

In this second part, we’ll look at the file handling of the program. The main function we’ll be looking at takes care of saving a text file to disk that has been translated. This is a really short tutorial, as the main part revolves around a trivial QTextStream to serialize the text from the translation.

    QString filename;

    if (!ui->resultLineEdit->toPlainText().count() == 0)
        filename = QFileDialog::getSaveFileName(this,
                                                "Save File",
                                                "Text files (*.txt)");
        QMessageBox::critical(this, "Pig Latin Translator",
                             "Make sure you have some results to save!");

    if (filename.isNull()) return;

    QFile file(filename);

    if (file.open(QIODevice::WriteOnly))
        QTextStream stream(&file);
        stream << ui->resultLineEdit->toPlainText();
        QMessageBox::critical(this, "Pig Latin Translator",
                              "Failed to open file for writing.");

The interesting parts are probably the file dialog we use, and the text stream (see highlighted parts). The static function provided by the file dialog gives you that native look-and-feel as well as a convenient way of not only getting a file path to save to, but also opening, etc. Text stream’s are basically the easiest possible way I can think of to write to a file in Qt. You simply pass a reference/pointer to an IO Device and use your left shift to write that text out!

Another interesting part that might trigger your curiosity is the critical message box. These message boxes are the annoying ones that popup in Windows XP with an “Unknown Error has occured”. Please, if you are going to use them (they are too easy to use, in my opinion :P), don’t pop up a thousand of them. Only use them to convey meaningful errors like this. File handling is a good place to use these, as the user needs to know what they did wrong so they can correct it–and it immediately requires their attention.

And that’s basically it for the program! Hope you enjoyed, and leave your questions/comments below or drop a like if you learned something. 🙂


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s