【问题标题】:how to redirect system output to my gui app (qt, linux)?如何将系统输出重定向到我的 gui 应用程序(qt、linux)?
【发布时间】:2013-07-16 02:05:54
【问题描述】:

我需要开发一个 GUI 程序来运行一些外部 bash 脚本。这个脚本工作大约 30-40 分钟,我想在我的应用程序中实时查看系统输出。

我怎样才能提供这个?我应该使用 QTextStream 吗?

请给我一些例子。

【问题讨论】:

    标签: linux qt output


    【解决方案1】:

    如果您通过 QProcess 启动脚本,您可以通过连接到 readyRead 信号来获取输出。然后只需调用任何读取函数来获取数据,然后将其显示在您想要的任何类型的小部件上,例如具有用于添加文本的附加功能的 QTextEdit。

    类似这样的:-

    // Assuming QTextEdit textEdit has been created and this is in a class
    // with a slot called updateText()
    QProcess* proc = new QProcess;
    connect(proc, SIGNAL(readyRead()), this, SLOT(updateText()));
    proc->start("pathToScript");
    
    ...
    
    // updateText in a class that stored a pointer to the QProcess, proc
    void ClassName::updateText()
    {
        QString appendText(proc->readAll());
        textEdit.append(appendText);
    }
    

    现在,每次脚本生成文本时,都会调用 updateText 函数并将其添加到 QTextEdit 对象中。

    【讨论】:

    • readyReadStandardError() 和 readyReadStandardOutput() 如果想同时捕获 stderr 和 stdout 但又想以不同方式处理它们。
    • 谢谢,它的作品,但前提是我这样做 proc->start 而不是 startDetached... 为什么会这样?
    • 糟糕,抱歉,这是我的错误。我会编辑答案。如果您调用 proc->start,我假设 Qt 保留了进程的句柄,可能将其作为子进程生成,但 startDetached,顾名思义,与进程分离,因此不会检索其输出。如果您确实需要将其分离,则需要查看 IPC 以了解您的应用程序和进程之间的通信。
    • @Merlin069 感谢您的详细回复!
    猜你喜欢
    • 2018-03-26
    • 1970-01-01
    • 2021-12-26
    • 1970-01-01
    • 1970-01-01
    • 2011-02-08
    • 2012-07-03
    • 1970-01-01
    • 2014-07-10
    相关资源
    最近更新 更多