Avrem Tan
Avrem Tan

Reputation: 11

Writing commands on linux terminal using Qt

I'm trying to get Qt creator to print a user input by using a push button on an UI into the terminal. As of now, the code is executable on the terminal via human input. Here is the code:

  void MainWindow::on_pushButton_clicked()
{
    QProcess::execute("/catkin_ws/devel/lib/submodbus");

    system("cd catkin_ws/devel/lib/submodbus");
    system("./submodbus_node");

}

Current output when using the code

Output via human input

The versions i'm running on are: -Ubuntu 16.04 -QT Creator 3.5.1

Upvotes: 1

Views: 1161

Answers (1)

JustWe
JustWe

Reputation: 4484

system can't change the current directory globally. but could use like this:

system("cd /catkin_ws/devel/lib/submodbus && ./submodbus_node");

or using QProcess::setProgram with QProcess::setWorkingDirectory

QProcess p;
p.setProgram("submodbus_node");
//p.setArguments(QStringList()<<args); // if you need
p.setWorkingDirectory("/catkin_ws/devel/lib/submodbus");
p.start();

or QDir::setCurrent

QDir::setCurrent("/catkin_ws/devel/lib/submodbus");
QProcess::startDetached("submodbus_node");

Test demo, create three files in the parent directory:

#include <QApplication>
#include <QProcess>
#include <QDir>

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

    system("cd ../ && touch test1.txt");

    QProcess p;
    p.setProgram("touch");
    p.setArguments(QStringList()<<"test2.txt");
    p.setWorkingDirectory("../");
    p.start();

    QDir::setCurrent("../");
    QProcess::startDetached("touch test3.txt");

    return a.exec();
}

Upvotes: 3

Related Questions