0

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

4

1 回答 1

1
  1. 在 C/C++ 字符串文字中,您必须转义所有反斜杠。

  2. waitForX()使用Qt 中的函数真的很糟糕。它们会阻止您的 GUI 并使您的应用程序无响应。从用户体验的角度来看,它确实很糟糕。不要这样做。

您应该使用信号和插槽以异步方式编写代码。

我的另一个答案提供了一个相当完整的示例,异步进程通信如何工作。它用于QProcess启动自身。

您的原始代码可以修改如下:

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.       
    }
    ...
}
于 2013-09-05T16:18:49.960 回答