【问题标题】:launching a program inside another program在另一个程序中启动一个程序
【发布时间】:2013-09-05 15:34:28
【问题描述】:

我试图让 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 示例,这对我来说没有意义。程序字符串的语法也正确,这行得通吗? 谢谢

【问题讨论】:

  • 使用/\\ 作为目录分隔符。 (是的,Windows 允许使用 /...)

标签: c++ qt qprocess


【解决方案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.       
    }
    ...
}

【讨论】:

    猜你喜欢
    • 2018-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多