Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. General and Desktop
  4. How to pass command line arguments from main.cpp to mainwindow.cpp
Forum Update on Monday, May 27th 2025

How to pass command line arguments from main.cpp to mainwindow.cpp

Scheduled Pinned Locked Moved Solved General and Desktop
4 Posts 3 Posters 5.4k Views
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • A Offline
    A Offline
    anuj nogja
    wrote on last edited by
    #1

    Hi All,
    I am passing two arguments when running my project from terminal in linux like
    ./project_exe <arg1> <arg2>
    These two values comes in main.cpp . Now i want to pass the values of these two arguments into a function defined in mainwindow.cpp.

    How this can be achieved?

    Kindly suggest...

    Regards,
    Anuj

    1 Reply Last reply
    0
    • SGaistS Offline
      SGaistS Offline
      SGaist
      Lifetime Qt Champion
      wrote on last edited by
      #2

      Hi,

      QCommandLineParser for the first part and then just call your MainWindow object function with the corresponding parameters.

      Interested in AI ? www.idiap.ch
      Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

      1 Reply Last reply
      3
      • mrjjM Offline
        mrjjM Offline
        mrjj
        Lifetime Qt Champion
        wrote on last edited by mrjj
        #3

        Hi
        what part is causing you an issue ?

        for only 2 arguments u can use plain c++

        int main(int argc, char* argv[]) {
          QApplication a(argc, argv);
          MainWindow w;
          w.show();
        // dump them :)
          for (int i = 1; i < argc; i++) {
            qDebug() << "param" << i << " is " << argv[i];
          }
        
          if (argc > 2 ) { 
            QString name(argv[1]);
            int id = atoi(argv[2]);
            qDebug() << "call func with" << id << " and " << name;
            w.MyLovelyFunction(id, name); // call some function in w mainwinow
          }
        

        in this test i call it like
        app.exe NAME 40
        so string and int.

        1 Reply Last reply
        3
        • A Offline
          A Offline
          anuj nogja
          wrote on last edited by
          #4

          Thanks for reply... it worked for me...

          1 Reply Last reply
          2

          • Login

          • Login or register to search.
          • First post
            Last post
          0
          • Categories
          • Recent
          • Tags
          • Popular
          • Users
          • Groups
          • Search
          • Get Qt Extensions
          • Unsolved