Frage

I'm trying to get Qt to launch another Qt program when a button is clicked. Here is my code.

void Widget::launchModule(){
    QString program = "C:\A2Q1-build-desktop\debug\A2Q1.exe";
    QStringList arguments;
    QProcess *myProcess = new QProcess(this);
    myProcess->start(program, arguments);
    myProcess->waitForFinished();
    QString strOut = myProcess->readAllStandardOutput();


}

So it is supposed to save into the QString strOut. First of all I am having an error with the QString program line I don't understand how to point this to the program as all examples of QProcess I have looked at use / and this doesn't make sense to me. Also with the syntax of the program string correct, will this work? Thanks

War es hilfreich?

Lösung

  1. In a C/C++ string literal, you must escape all backward slashes.

  2. It's really bad to use the waitForX() functions in Qt. They block your GUI and make your application unresponsive. From a user experience point of view, it truly sucks. Don't do it.

You should code in asynchronous style, with signals and slots.

My other answer provides a rather complete example how asynchronous process communications might work. It uses QProcess to launch itself.

Your original code could be modified as follows:

class Window : ... {
    Q_OBJECT
    Q_SLOT void launch() {
        const QString program = "C:\\A2Q1-build-desktop\\debug\\A2Q1.exe";
        QProcess *process = new QProcess(this);
        connect(process, SIGNAL(finished(int)), SLOT(finished()));
        connect(process, SIGNAL(error(QProcess::ProcessError)), SLOT(finished()));
        process->start(program);
    }
    Q_SLOT void finished() {
        QScopedPointer<Process> process = qobject_cast<QProcess*>(sender());
        QString out = process->readAllStandardOutput(); 
        // The string will be empty if the process failed to start
        ... /* process the process's output here */
        // The scoped pointer will delete the process at the end 
        // of the current scope - right here.       
    }
    ...
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top