1. 程式人生 > >Qt 解析命令行參數

Qt 解析命令行參數

etc info must 技術分享 程序 led [] 版本 png

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQuickView>
#include <QCommandLineParser>

int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);
    QGuiApplication::setApplicationName("Qt");  // 應用名稱
    QGuiApplication::setApplicationVersion(
"0.1"); // 應用版本號 QCommandLineParser parser; parser.setApplicationDescription(QGuiApplication::translate("main", "Qt")); // 設置應用程序描述信息 parser.addHelpOption(); // 添加幫助選項 ("-h" 或 "--help") parser.addVersionOption(); // 添加版本選項 ("-v" 或 "--version") parser.setSingleDashWordOptionMode(QCommandLineParser::ParseAsLongOptions); // 舉例說明:將 "-adb" 當成一個選項來看,而不是看成 "-a -b -c"
// parser.addPositionalArgument("xxx", QGuiApplication::translate("main", "?????? undefined")); QCommandLineOption widthOption(QStringList() << "wid" << "width", QGuiApplication::translate("main", "Width of the covered area (default is 800)."), QGuiApplication::translate(
"main", "width"), "800"); parser.addOption(widthOption); QCommandLineOption heightOption(QStringList() << "hei" << "height", QGuiApplication::translate("main", "Height of the covered area (default is 480)."), QGuiApplication::translate("main", "height"), "480"); parser.addOption(heightOption); QCommandLineOption xOption(QStringList() << "x", QGuiApplication::translate("main", "The x coordinate of the covered area (default is 0)."), QGuiApplication::translate("main", "x"), "0"); parser.addOption(xOption); QCommandLineOption yOption(QStringList() << "y", QGuiApplication::translate("main", "The y coordinate of the covered area (default is 0)."), QGuiApplication::translate("main", "y"), "0"); parser.addOption(yOption); QCommandLineOption colorOption(QStringList() << "c" << "color", QGuiApplication::translate("main", "The color of the covered area (default is black)."), QGuiApplication::translate("main", "color"), "black"); parser.addOption(colorOption); parser.process(app); // const QStringList args = parser.positionalArguments(); int width = parser.value(widthOption).toInt(); int height = parser.value(heightOption).toInt(); if (0 > width || 0 > height) { fprintf(stderr, "%s\n", qPrintable(QGuiApplication::translate("main", "Error: Invalid format argument. " "Width and height must be greater than 0."))); parser.showHelp(1); } int x = parser.value(xOption).toInt(); int y = parser.value(yOption).toInt(); QString color = parser.value(colorOption); QQuickView view; view.setGeometry(x, y, width, height); view.setColor(QColor(color)); view.setFlags(Qt::FramelessWindowHint); // view.setSource(QUrl("qrc:/main.qml")); view.show(); return app.exec(); }

效果:

技術分享圖片

Qt 解析命令行參數