//Create parser object QCommandLineParser parser; parser.setApplicationDescription("An application for testing QCommandLineParser"); //Define possible options QCommandLineOption helpOption("h", QCoreApplication::translate("main", "Display help message.")); parser.addOption(helpOption); QCommandLineOption messageOption("m", QCoreApplication::translate("main", "The message to display."), QCoreApplication::translate("main", "message")); parser.addOption(messageOption); //Process the command-line arguments parser.process(QCoreApplication::arguments()); //Retrieve the values if (parser.isSet(helpOption)) { parser.showHelp(0); } if (parser.isSet(messageOption)) { QString message = parser.value(messageOption); qDebug() << message; }
//Create parser object QCommandLineParser parser; parser.setApplicationDescription("An application for calculating the area of a rectangle"); //Define possible options QCommandLineOption widthOption("w", QCoreApplication::translate("main", "The width of the rectangle."), QCoreApplication::translate("main", "width")); parser.addOption(widthOption); QCommandLineOption heightOption("h", QCoreApplication::translate("main", "The height of the rectangle."), QCoreApplication::translate("main", "height")); parser.addOption(heightOption); //Process the command-line arguments parser.process(QCoreApplication::arguments()); //Calculate the area if (parser.isSet(widthOption) && parser.isSet(heightOption)) { double width = parser.value(widthOption).toDouble(); double height = parser.value(heightOption).toDouble(); double area = width * height; qDebug() << "Area:" << area; }This example creates a parser object, defines two possible options (-w for width and -h for height), processes the command-line arguments, and calculates the area of a rectangle if both options are set. The QCommandLineParser belongs to the QtCore package library.