[ fromfile: qtfirstapp.xml id: qtfirstapp ]
Example 1.15. src/early-examples/example1/fac1.cpp
#include <QtGui> int main (int argc, char* argv[]) { QApplication app(argc, argv); QTextStream cout(stdout); // Declarations of variables int answer = 0; do { // local variables to the loop: int factArg = 0; int fact(1); factArg = QInputDialog::getInt(0, "Factorial Calculator", "Factorial of:", 1); 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) .arg("Compute another factorial?"); answer = QMessageBox::question(0, "Play again?", response, QMessageBox::Yes | QMessageBox::No); } while (answer == QMessageBox::Yes); return EXIT_SUCCESS; }
Start of function "main" which returns int. | |
Start of every Qt GUI application. | |
Create a QTextStream to standard output. | |
Must be defined outside the do loop because it is used in the condition outside the do block. | |
Pop up dialog, wait for user to enter an integer, return it. | |
Each %n is replaced with an arg() value. | |
Long statements can continue on multiple lines, as long as they are broken on token boundaries. | |
Bitwise or of two values. |
This program makes use of the Qt types (classes) listed next.
QApplication – A single object that needs to exist in Qt GUI applications.
QInputDialog – For asking questions of the user.
QMessageBox – For sending responses back to the user.
QString – A unicode string class. This example uses the powerful QString function arg()
, which enables you to format parameterized values (%1, %2, etc.) into the string.
QTextStream – For streaming to/from text files. In this example, we defined a variable called cout
that goes to the same place (stdout)
as the iostream
cout
from the C++ standard library. If you intend to get user input from dialogs and other widgets, there is no need for cin
anymore.
When you run this application, you first see an input dialog like Figure 1.2.
After the user enters a number and clicks OK, the dialog box is replaced with a QMessageBox that pops up with the calculated result.
Any application that uses Qt classes needs a project file.
Example 1.16. src/early-examples/example1/example1.pro
TEMPLATE = app include (../../common.pri) SOURCES += fac1.cpp
TEMPLATE = app
, indicates that qmake
should start with a templated Makefile
suited for building applications.
The second line includes the optional common project settings from Example 1.6.
Finally, the source file is listed in SOURCES
.
Generated: 2012-03-02 | © 2012 Alan Ezust and Paul Ezust. |