Qt World Summit: Register Today!

A problem about Receiving integer arguments

  • Hello everybody...
    I have a little problem with QT environment.... I want my application DataViewer.cpp to receive two integer arguments d1 , d2 from the user by argv then I want to employ them inside the main class DataViewer::DataViewer
    I used this piece of code but it doesn't convert the Qstrings to integer:
    @QStringList args = qApp->arguments();
    int cc;
    cc = args.size();
    int d1,d2;
    QString d1_str,d2_str;
    d1_str = qApp->arguments().at(1);
    d2_str = qApp->arguments().at(2);

    bool result;
    d1 = d1_str.toInt(&result, 10);
    d2 = d2_str.toInt(&result, 10);@

    Then I tried to use:

    @QByteArray ba1 = d1_str.toLocal8Bit();
    QByteArray ba2 = d2_str.toLocal8Bit();
    const char *c_strd1 = ba1.data();
    const char *c_strd2 = ba2.data();
    d1= atoi (c_strd1);
    d2= atoi (c_strd2);@

    but I couldn't receive the integer values of d1, d2 like : DataViewer 1 3

    Anybody can help me please...
    Thank you.

    [EDIT: code formatting, please wrap in @-tags, Vass]

  • Why you use a atoi?
    Try this:

    @QStringList sl = a.arguments();
    QString myString;
    myString = sl.at( 1 );

    int myInt;
    myInt = b.toInt();

    qDebug() << myInt; // integer value@

    [EDIT: code formatting, please wrap in @-tags, Vass]

  • Because (as he said) he tried QString::toInt() but failed...

    The snippet you provided should work just fine. I just created "a simple test case":https://gist.github.com/1215612 that works correctly on my machine.

  • A few annotations:

    • Please wrap your code with @ tags. This way it is formatted properly.
    • You should store the result of QCoreApplication::arguments(), because calling it is slow.

    Besides that it should work as listed in your code snippet.

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

    QStringList arguments = application.arguments();
    int firstArgument = arguments.at(1).toInt();
    int secondArgument = arguments.at(2).toInt();
    qDebug() << firstArgument << secondArgument;
    return 0;


  • @uranusjr thanks a lot ... it works with me and thank you everybody :)

Log in to reply