I want to start cmd.exe
with QProcess
without startDetached
because I need to interact with the running cmd. and the cmd has to be in forground. and I want to get readyRead()
once the first process completes and then I'll do some other tasks, like showing some message box or launching another cmd.exe or executing another command in that cmd window. But the cmd window must be visible to user.
2 Answers
It sounds like you want to run a command-line process (or several), display its output while it runs, and then run another process when it's done.
I usually do this by having a read-only QPlainTextEdit in my main window to display io to the command-line. Create a QProcess on the heap and connect
its readyReadStandardError and readyReadStandardOutput signals to a slot in your main window that prints the text to your QPlainTextEdit. Then launch your command-line program with arguments with QProcess::start and wait for it to finish. Once it finishes, start your next process the same way.

- 3,704
- 28
- 61
-
There's a very nice example of how to create the console window repurposed from a QPlainTextEdit in the "SerialPort" EXAMPLES section of the Qt Creator, fyi. – Rachael Feb 26 '15 at 21:42
You could also just enable a console in Qt along side your GUI.
Console output in a Qt GUI app?
And then use qDebug
calls to put text out to the debug window or use iostream
with std::cout
and std::cin
.
EDIT: To show the console, in your .pro add "CONFIG += console" and then in your Project > Run settings, be sure to check "Run in terminal".
EDIT2:
https://www.google.com/search?q=qprocess+cmd
http://www.qtcentre.org/threads/12757-QProcess-cmd
#include <QByteArray>
#include <QProcess>
#include <iostream>
#include <string>
using namespace std;
int main(int argc,char** argv)
{
QProcess cmd;
cmd.start("cmd");
if (!cmd.waitForStarted())
return false;
cmd.waitForReadyRead();
QByteArray result = cmd.readAll();
cout << result.data();
string str;
getline(cin,str);
while(str != string("exit"))
{
cmd.write(str.c_str());
cmd.write("\n");
cmd.waitForReadyRead();
result = cmd.readAll();
cout << result.data();
getline(cin,str);
}
}
I tested the code here, and it lets you interact with the commandline and get the output back through readyread(), but if you are running it with a GUI, you will need to move this while loop from the main to happen in another thread.
-
I don't need to print anything in console window. and I don't see anywhere I mentioned any such thing in question. What I need is just to run a visible cmd.exe window and interact with it. – Dipro Sen Feb 20 '13 at 18:10
-
You want the console window visible but you don't want to print to it? What do you mean "interact with it"? – Phlucious Feb 20 '13 at 21:01