QInputDialog and QMessageBox

Barry Michael Doyle picture Barry Michael Doyle · Apr 29, 2015 · Viewed 11.6k times · Source

I'm doing some preparation for an exam using Qt framework and I would like to know how to use QInputDialog and QMessageBox in a basic way (my exams are hand written coding)

The Qt API is really confusing to understand when it comes to using and it was fine for my projects because I could accomplish what I wanted in a really "hacky" way a my set book on the subject is very poorly laid out...

Let me get to the point, what would be a clean way of using QInputDialog and QMessageBox in this scenario:

#include <QApplication>
#include <QInputDialog>
#include <QDate>
#include <QMessageBox>

int computeAge(QDate id) {
  int years = QDate::currentDate().year() - id.year();
  int days = QDate::currentDate().daysTo(QDate
              (QDate::currentDate().year(), id.month(), id.day()));
  if(days > 0) 
    years--;
  return years
}

int main(int argc, char *argv[]) {
  QApplication a(argc, argv);
  /*  I want my QInputDialog and MessageBox in here somewhere */
  return a.exec();
}

For my QInputDialog I want the user to give their birth date (don't worry about input validation) I want to use the QMessageBox to show the user's age

I just don't understand what parameters need to go into the QInputDialog and QMessageBox in a basic case like because there don't seem to be any examples out there.

How would I accomplish this?

Answer

vahancho picture vahancho · Apr 29, 2015

You can do something like:

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    bool ok;
    // Ask for birth date as a string.
    QString text = QInputDialog::getText(0, "Input dialog",
                                         "Date of Birth:", QLineEdit::Normal,
                                         "", &ok);
    if (ok && !text.isEmpty()) {
        QDate date = QDate::fromString(text);
        int age = computeAge(date);
        // Show the age.
        QMessageBox::information (0, "The Age",
                                  QString("The age is %1").arg(QString::number(age)));
    }
    [..]