我试图从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
我怎么解决这个问题?
你必须使用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});
您不能使用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);