Retrieving command line arguments in a Qt application

c++, qt

Solution

You better use `QCoreApplication::arguments`

Basically, you would need to use it like this:

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();
    w.setGeometry(QRect(QPoint(100,100), QSize(1000,500)));

    CHat *hat = new CHat();
    hat->color(QCoreApplication::arguments().at(1));

    return a.exec();
}

Then you invoke the following command: `./countHats red`. There is no need for quotes in this particular case, nor for brackets, although it will work with quotes, too.

You would need the quotes if you have an argument that contains spaces, and so forth, which is not the case with the very simple colors, and for a bit more, you would need color code management, anyhow.

PS, why we are at it, you should use a better name for your setter like `setColor`. `color()` is usually used for getting the value of the color, not setting that, but that is slightly off-topic now. I just wished to help you with pointing that out, too.

Also, you do not seem to delete the hat, and it does not take part in the Qt parent/child relationship either to get automatically deleted. You would need to improve this bit, too.

Note however that me and David Faure have been working on a `QCommandLineParser` class which you can hopefully use from Qt5.2 on. Changes are now being reviewed on gerrit for integration.

Problem

I want to do something like from the Unix command prompt: ``` ./countHats("red") or ./countHats "red" ``` and then the program runs and counts up red hats. How can I do that? ``` int main(int argc, char *argv[]) { QApplication a(argc, argv); MainWindow w; w.show(); w.setGeometry(QRect(QPoint(100,100), QSize(1000,500))); CHat *hat = new CHat(); hat->color(argv[0]);//"red" ???? return a.exec(); } ```

Original source