Dipro Sen
Dipro Sen

Reputation: 4670

Qt launch cmd.exe

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.

Upvotes: 0

Views: 7855

Answers (2)

Phlucious
Phlucious

Reputation: 3843

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.

Upvotes: 1

phyatt
phyatt

Reputation: 19152

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.

Upvotes: 0

Related Questions