1.11.  Qt Dialogs for User Input/Output

[ fromfile: qtfirstapp.xml id: qtfirstapp ]

Example 1.15. src/early-examples/example1/fac1.cpp

#include <QtGui>

int main (int argc, char* argv[]) {                 1
    QApplication app(argc, argv);                   2
    QTextStream cout(stdout);                       3

    // Declarations of variables
    int answer = 0;                                 4

    do {
        // local variables to the loop:
        int factArg = 0;
        int fact(1);
        factArg = QInputDialog::getInt(0, "Factorial Calculator",
            "Factorial of:", 1);                    5
        cout << "User entered: " << factArg << endl;
        int i=2;
        while (i <= factArg) {
            fact = fact * i;
            ++i;
        }
        QString response = QString("The factorial of %1 is %2.\n%3")
            .arg(factArg).arg(fact)                 6
            .arg("Compute another factorial?");     7
        answer = QMessageBox::question(0, "Play again?", response,
            QMessageBox::Yes | QMessageBox::No);    8
    } while (answer == QMessageBox::Yes);
    return EXIT_SUCCESS;
}

1

Start of function "main" which returns int.

2

Start of every Qt GUI application.

3

Create a QTextStream to standard output.

4

Must be defined outside the do loop because it is used in the condition outside the do block.

5

Pop up dialog, wait for user to enter an integer, return it.

6

Each %n is replaced with an arg() value.

7

Long statements can continue on multiple lines, as long as they are broken on token boundaries.

8

Bitwise or of two values.


Figure 1.2.  QInputDialog – Getting an int

QInputDialog – Getting an int

Figure 1.3.  QMessageBox Question

QMessageBox Question

More About Project Files

Example 1.16. src/early-examples/example1/example1.pro

TEMPLATE = app
include (../../common.pri)
SOURCES += fac1.cpp