2013-09-05 37 views
0

我试图让Qt在单击按钮时启动另一个Qt程序。 这是我的代码。在另一个程序中启动程序

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(); 


} 

所以它应该保存到QString strOut。首先,我在QString程序中出现错误,我不明白如何将这个程序指向程序,因为QProcess的所有示例都使用了/这对我来说没有任何意义。此外与程序字符串的语法正确,这将工作? 感谢

+2

用途是'/'或''\\作为目录分隔符。 (是的,Windows允许使用'/'...) – Joni

回答

1
  1. 在C/C++字符串字面量,你必须逃避所有反斜杠。

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

您应该使用信号和插槽进行异步编码。

我的other answer提供了一个非常完整的例子,说明异步过程通信如何工作。它使用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.  
    } 
    ... 
} 
相关问题