jdl
jdl

Reputation: 6323

Retrieving command line arguments in a Qt application

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();
}

Upvotes: 7

Views: 26864

Answers (3)

László Papp
László Papp

Reputation: 53145

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.

Upvotes: 16

jantar
jantar

Reputation: 183

First of all for any app in C/C++: first element of argv is name of the program, so argv[0] will be "countHats" not "red". And If You want to have more command line arguments I recommend using boost::program_options library, it's quite easy to use and very powerful. http://www.boost.org/doc/libs/1_54_0/doc/html/program_options.html

Upvotes: 2

jdl
jdl

Reputation: 6323

code should be argv[1]...

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[1]);//"red"   ????  -->  argv[1]

    return a.exec();
}

this works for the commandLine:

./countHats "red"   or 
./countHats red

Upvotes: 2

Related Questions