Question

I'm writing a small console app in Qt and I want to be able to clear the terminal on a user command. I found this:

How clear screen in QT console?

which almost answers my question, but its not working.

When the function "QProcess::execute("clear");" is run, I get this output to the terminal:

TERM environment variable not set.

I'm pretty new to Linux and though I've set environment variables before, its always been in the terminal before I ran the program. Here, I'd like to take care of this programmatically if possible.

My guess is that I could use QProcess::setProcessEnvironment() but I'm not really sure how exactly.

Is it possible to set the environment variables in this way, and if so how?

Any help would be greatly appreciated!

Here's the sample code I'm working with:

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    QTextStream qin(stdin);
    QTextStream qout(stdout);
    QString cmd;

    while(1)
    {
        cmd = qin.readLine();

        qout<<"command is: "<<cmd<<endl;

        if(cmd == "clear")
        {
            QProcess::execute("clear");
        }
    }
    return a.exec();
}
Was it helpful?

Solution

The code below works fine for me. Please make sure that the clear command works fine in your console first.

main.cpp

#include <QProcess>
#include <QDebug>

int main()
{
    QProcess::execute("clear");
    qDebug() << QProcessEnvironment::systemEnvironment().contains("TERM");
    return 0;
}

main.pro

TEMPLATE = app
TARGET = main
QT = core
SOURCES += main.cpp

Build and Run

qmake && make && ./main

Note that if you are using QtCreator, you will need add the environment variable with its value explicitly in the build settings tab. Here you can find more details in the documentation:

QtCreator - Using Environment Variables

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top