3

I am trying to read the screen resolution from within a Qt application, but without using the GUI module.

So I have tried using:

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

command through QProcess, but it shows a warning and does not give any output:

unknown escape sequence:'\\*'

Rewriting it with \\\* does not help, as it leads to the following error:

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

How can I solve that?

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Som
  • 185
  • 15

2 Answers2

7

You have to use bash and pass the argument in quotes:

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

Output:

"1366x768\n"

Or:

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

Or:

QProcess process;
QString command = R"(xrandr |grep \* |awk '{print $1}')";
process.start("/bin/sh", {"-c" , command});
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
2

You can't use QProcess to execute piped system commands like that, it is designed to run a single program with arguments Try:

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

OR

QProcess process;
QStringList args = QString("-c,xrandr,|,grep *,|,awk '{print $1}'").split(",");
process.start("bash", args);
Marker
  • 972
  • 6
  • 9
  • thanks, while this one do get me a result , this is printing the entire command output without filtering the first one. – Som Sep 10 '18 at 20:57
  • still same issues. while on command line xrandr gives 1366x768 output. It gives the entire value through QProcess, Screen 0: minimum 320 x 200, current 1366 x 768, maximum 8192 x 8192\neDP-1 connected primary 1366x768+0+0 (normal left inverted right x axis y axis) 344mm x 194mm\n 1366x768 59.97*+\n 1280x720 60.00 59.99 59.86 59.74 \n 1024x768 60.04 60.00 \n 960x720 60.00 \n 928x696 60.05 \n 896x672 60.01 ... – Som Sep 10 '18 at 21:02
  • What is the actual string (format) that you are trying to filter out? – Marker Sep 10 '18 at 21:06
  • Sorry, resolution like format , like this 1366x768. – Som Sep 10 '18 at 21:08
  • Yeah, I see now, it doesn't seem to be passing the output through grep. You could just use the process to call xrandr, read the output and use a regular expression to pull out the info you want. – Marker Sep 10 '18 at 21:25