3

我正在尝试从 Qt 应用程序中读取屏幕分辨率,但不使用 GUI 模块。

所以我尝试使用:

xrandr |grep \* |awk '{print $1}'

通过QProcess命令,但它显示警告并且不提供任何输出:

unknown escape sequence:'\\*'

重写它\\\*没有帮助,因为它会导致以下错误:

/usr/bin/xrandr: unrecognized option '|grep'\nTry '/usr/bin/xrandr --help' for more information.\n

我该如何解决?

4

2 回答 2

7

您必须使用 bash 并在引号中传递参数:

#include <QCoreApplication>
#include <QProcess>
#include <QDebug>

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    QProcess process;
    QObject::connect(&process, &QProcess::readyReadStandardOutput, [&process](){
       qDebug()<<process.readAllStandardOutput();
    });
    QObject::connect(&process, &QProcess::readyReadStandardError, [&process](){
       qDebug()<<process.readAllStandardError();
    });
    process.start("/bin/bash -c \"xrandr |grep \\* |awk '{print $1}' \"");
    return a.exec();
}

输出:

"1366x768\n"

或者:

QProcess process;
process.start("/bin/bash", {"-c" , "xrandr |grep \\* |awk '{print $1}'"});

或者:

QProcess process;
QString command = R"(xrandr |grep \* |awk '{print $1}')";
process.start("/bin/sh", {"-c" , command});
于 2018-09-10T21:16:40.887 回答
2

您不能使用 QProcess 来执行这样的管道系统命令,它旨在运行带有参数的单个程序尝试:

QProcess process;
process.start("bash -c xrandr |grep * |awk '{print $1}'");

或者

QProcess process;
QStringList args = QString("-c,xrandr,|,grep *,|,awk '{print $1}'").split(",");
process.start("bash", args);
于 2018-09-10T20:42:35.797 回答