Running C ++ binary from within Qt and redirecting the output of the binary to the textbox of a Qt application

I want to run a C ++ binary that I created from a Qt application. How is this possible? In Java, I had something like Runtime.exec()

. Could you please tell me how this is possible within Qt?

Also, while my binary is working, I want the output of this program (which is now being written to the console) to be written to a text field in Qt. I can easily do textbox.setText () if I had the data written to the console in a string. So the main question is how to access the data that the program is supposed to write to the console while it is actually being run from within the Qt framework.

I know I can solve both of the above problems by simply executing and compiling my code from Qt, but I am asking because I am in the middle of a time gap and some design issues. If this reason doesn't sail your boat, kindly think of the question as homework and help me :)

+3


source to share


2 answers


QProcess is your friend.

Something close to the minimal version of some code that invokes the Windows command interpreter and waits synchronously to output it to get a simple directory listing would look like this:

QProcess process;
process.start("cmd.exe",
              QStringList() << "/c" << "dir" << "/b",
              QIODevice::ReadWrite | QIODevice::Text);
if(!process.waitForFinished()) // beware the timeout default parameter
    qDebug() << "executing program failed with exit code" << process.exitCode();
else
    qDebug() << QString(process.readAllStandardOutput()).split('\n');

      

This gets more interesting if you want to run it asynchronously and get "online" results, perhaps inside a Qt-GUI application, to update the progress bar. You will have a customization piece for example. inside your main form constructor line by line:

process = new QProcess(this);
connect( process, SIGNAL(readyReadStandardOutput()), SLOT(onStdoutAvailable()) );
connect( process, SIGNAL(finished(int,QProcess::ExitStatus)), SLOT(onFinished(int,QProcess::ExitStatus)) );

      



Perhaps in the button clicked, the handler will call something like:

process->start("some_command", QStringList() << "some" << "args",
               QIODevice::ReadWrite | QIODevice::Text);
if(!process->waitForStarted())
    // some_command failed to even start

      

Then call process-> readAllStandardOutput () in your onStdoutAvailable () slot and parse it somehow to determine your progress. Finally, evaluate the exitCode and exitStatus parameters of the connected ready () signal to determine if everything is OK (TM).

It starts to get fun if you want to be able to stop / kill a process and all potential child processes without their consent and make this cross platform ... but that is obviously beyond the scope of your question.

+6


source


Have a look at QProcess and its methods, especially readAllStandardOutput ()



+3


source







All Articles