QT: running a program with arguments

Continue from my post about how to passing argument in C/C++, now I try to create a tutorial in Qt about how to running program with argument (command line argument in Qt / Qt passing argument). In Qt, we can use class QApplication::arguments() to get argument from program. From this command, we get QStringList with information about all input argument from our program. First argument from this function is name of our program. So, we can get input argument from our program from second index. Example :

We can running our program with command (command line argument in Qt / Qt passing argument):

ourProgramName param1 param2

Information from command above is :

argument[0]=ourProgramName

argument[1]=param1

argument[2]=param2

This is a simple code at main.cpp to get input argument from Qt :<!–more–>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    qt_runArgument *w;

    QStringList theArgs = QApplication::arguments();

    if(theArgs.count()>1)
        w = new qt_runArgument(theArgs.at(1));
    else
        w = new qt_runArgument();

    w->show();
    return a.exec();
}

We can modified class qt_runArgument.cpp in constructor with :

qt_runArgument::qt_runArgument(QString filename, QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::qt_runArgument)
{
    ui->setupUi(this);

    if(filename.count()>0)
        readFileParameter(filename);
}

This is example for my program about how to implementated running a program with argument in Qt. I create simple text viewer in Qt. We can run this program from terminal (Qt command line argument / Qt passing argument) or from desktop (right click icon in desktop). We can running this program from terminal (Qt command line argument/ Qt passing argument) with command :

./qt_runargument (running without argument)

./qt_runargument main.cpp (running with argument)

If we running this program with argument, program will open file in argument input and display in window. We can run this program in desktop to by use right click over an file. Use open with menu and use qt_runargument as program to open that file.

Output program from code Qt running a program with arguments is :

Qt Run With Argument
Qt Run With Argument

You can get the complete code for this program in here.

2 Comments

Add a Comment

Your email address will not be published. Required fields are marked *