I want to fire a c++ binary that I generated from inside a Qt Application. How is this possible ? In Java I had something like Runtime.exec()
. Can you please tell me how this is possible in the Qt framework ?
Also, While my binary is running, I want the output of that program (which is now written to the console) to be written to a textbox in Qt. I can easily do a textbox.setText() if I had the data that is written on the console in a string. So basically the question is how to get your hands on the data the program is supposed to be writing to the console while it is in fact being run from inside the Qt framework.
I know I can solve both the above issues by simply running and compiling my code from inside Qt, but I am asking because I am in the middle of a sever time crunch and some gaping design issues. If this reason does not float your boat, kindly think of the question as a homework question and help me :)
QProcess is your friend.
Something close to a minimal version of some code that calls the Windows command interpreter and waits synchronously for its output to get a simple directory listing would look like:
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');
It gets more interesting if you want to run it asynchronously and get 'online' results maybe inside a Qt-GUI application to update a progress bar, say. You would have a setup part e.g. inside your main form constructor along the lines of:
process = new QProcess(this);
connect( process, SIGNAL(readyReadStandardOutput()), SLOT(onStdoutAvailable()) );
connect( process, SIGNAL(finished(int,QProcess::ExitStatus)), SLOT(onFinished(int,QProcess::ExitStatus)) );
Maybe in a button pressed handler 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() inside your onStdoutAvailable() slot and parse it somehow to determine your progress. And finally evaluate the exitCode and exitStatus parameters of the connected finished() signal to determine whether everything 'is ok (TM)'.
It starts to get fun if you want to be able to stop/kill the process and all potential child processes without their consent and do that cross platform... but that seems obviously out of the scope of your question.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With