c++linuxqtqt5xrandr

How to execute a shell command under Linux unsing QProcess?


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?


Solution

  • 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});