The standard way to use Qprocess is as follows:
QObject *parent;
...
QString program = "./path/to/Qt/examples/widgets/analogclock";
QStringList arguments;
arguments << "-style" << "motif";
QProcess *myProcess = new QProcess(parent);
myProcess->start(program, arguments);
However, What I am trying to do is running the binary on the console (sh) and then copying the output from there to the textbox in Qt.
So now what I need to do in myProcess->start(program, arguments); is to pass sh in program and the binary name in arguments. But what if my binary takes commandline arguments too ? Where do i supply it ?
You can use arguments() :
#include <QApplication>
...
QStringList myArgs = qApp->arguments();
myProcess->start(program, myArgs);
I tried this:
/home/user/1.sh
#!/bin/sh
echo $1 >> /home/user/1.out
echo $2 >> /home/user/1.out
echo $3 >> /home/user/1.out
main.cpp
#include <QtCore>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QString program = "sh";
QStringList args;
args << "/home/user/1.sh" << "qwe" << "123" << "c c c";
QProcess p;
p.start(program, args);
p.waitForFinished();
return 0;
}
After running my app, I got:
1.out
qwe
123
c c c
Seems working for me.
Related
When I run my C++ program I need it to open a text file stored in my root directory. How can I make CMake to execute the program I have written with the text file?
When I build my program with Makefile alone, I use the command
./"executable" src/"txt file"
Honestly, by far the simplest would be to just modify your main function. As it stands you main function must be grabbing the filename from the command line arguments. Something like this:
#include <iostream>
int main(int argc, char *argv[]) {
const auto filename = argv[1];
// Do stuff with filename
std::cout << filename;
return 0;
}
What you probably should do is to just modify that file to use some default filename when no argument is provided:
#include <iostream>
int main(int argc, char *argv[]) {
const auto filename = argc < 2 ? "/root/something.txt" : argv[1];
// Do stuff with filename
std::cout << filename;
return 0;
}
Depending on how complicated you want to get, you could also let that filename be specified in your CMakeLists. Just add a definition like
set(DEFAULT_FILENAME "/root/something.txt")
target_compile_definitions(my_target PRIVATE "DEFAULT_FILENAME=\"${DEFAULT_FILENAME}\"")
and then take the filename like a macro in your main function:
#include <iostream>
int main(int argc, char *argv[]) {
const auto filename = argc < 2 ? DEFAULT_FILENAME : argv[1];
// Do stuff with filename
std::cout << filename;
return 0;
}
To summarize... It sounds like you want to have one executable to be built with the filename into it. The aforementioned approaches will accomplish that.
However, there is a much simpler solution... just create a script that runs the file you want. For example, just throw your code
./"executable" src/"txt file"
into a script run.sh
Then make that script runnable (assuming Linux) with
chmod +x run.sh
and just run that script:
./run.sh
I am using Qt (5.5) and I want to exchange data in JSON format in a client-server application.
So the format is constant:
{
"ball":
{
"posx": 12,
"posy": 35
}
}
I would like to be able to define a ByteArray or string like so:
QByteArray data = "{\"ball\":{\"posx\":%s,\"posy\":%s}}"
and then just write whatever the values for that into the string.
How do I do that?
QtJson is baked into Qt 5. It is easy to use, and gets it all ready for you pretty easily.
#include <QCoreApplication>
#include <QDebug>
#include <QJsonObject>
#include <QJsonDocument>
void saveToJson(QJsonObject & json);
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QJsonObject jsonObject;
saveToJson(jsonObject);
QJsonDocument jsonDoc(jsonObject);
qDebug() << "Example of QJsonDocument::toJson() >>>";
qDebug() << jsonDoc.toJson();
qDebug() << "<<<";
return a.exec();
}
void saveToJson(QJsonObject & json)
{
QJsonObject ball;
ball["posx"] = 12;
ball["posy"] = 35;
json["ball"] = ball;
}
output
Example of QJsonDocument::toJson() >>>
"{
"ball": {
"posx": 12,
"posy": 35
}
}
"
<<<
Note: qDebug() wraps QString objects in quotes when printing. To get rid of that, pass your QString into qPrintable(). And it puts endl in for you at the end of each line.
For a more complex example see the official:
JSON Save Game Example
http://doc.qt.io/qt-5/qtcore-json-savegame-example.html
Hope that helps.
And here are more examples of string manipulations, but for readability and maintainability, please use the QJson classes.
QString str;
str = QString("{\"ball\":{\"posx\":%1,\"posy\":%2}}").arg(12).arg(35);
qDebug() << qPrintable(str);
QByteArray ba = str.toLocal8Bit();
qDebug() << ba;
QString str2;
str2 = "{\"ball\":{\"posx\":"
+ QString::number(12)
+ ",\"posy\":"
+ QString::number(35)
+ "}}";
qDebug() << qPrintable(str2);
output
{"ball":{"posx":12,"posy":35}}
"{"ball":{"posx":12,"posy":35}}"
{"ball":{"posx":12,"posy":35}}
Note again that the quotes are added by qDebug() when printing a QByteArray object.
Hope that helps.
I am writing a small application on linux using qt creator.
When i start my application i want it to execute a shell command. I`m using QProcess for it like this:
int main(int argc, char *argv[])
{
MyApplication a(argc, argv);
QProcess mapProc(&a);
QString command;
QStringList args;
command = "java";
args << "-jar" << "/home/$USER/MapServer/map.jar" << "localhost" << "9797" << "12123";
mapProc.start(command, args);
bool flag = mapProc.waitForStarted();
QProcess::ProcessState state = mapProc.state();
qDebug() << mapProc.errorString();
qDebug() << mapProc.pid();
/*/////////////////
some code
/////////////////*/
return a.exec();
}
but when my application started, process "mapProc" becomes a zombie. Why? what am i doing wrong?
$USER will not really work like that with QProcess. You will need to invoke the command through /bin/sh -c "mycmd" or even better if you just do it the proper Qt way as indicated below.
Try using QStandardPaths, so write this:
QString homeLocation =
QStandardPaths::standardLocations(QStandardPaths::HomeLocation);
args << "-jar" << QString(homeLocation.first() + "/MapServer/map.jar")
<< "localhost" << "9797" << "12123";
instead of this:
args << "-jar" << "/home/$USER/MapServer/map.jar"
<< "localhost" << "9797" << "12123";
I have an application that when run through terminal, the user has the option between command-line mode or GUI mode.
There doesn't seem to be any output to the console at all when using std::cout. std::cout statements don't work in the main event loop.
I have added CONFIG += console to my .pro file.
For now, I have been using QTextStream() which works fine:
QTextStream(cout) << "Hello World" << std::endl;
My question is:
Why can I not use std::cout? Does this have something to do with Qt affecting input and output streams? I couldn't find any documentation in Qt's docs on this.
int main(int argc, char *argv[])
{
std::cout << argv[1] << std::endl; //This is being outputted.
//if(argc == 2 && !strcmp(argv[1],"-win")){
if(true){ //Just for this example's sake
QApplication a(argc, argv);
std::cout << "Hello" << std::endl; //This is not being ouputted.
MainWindow w;
w.show();
return a.exec();
}
else
{
qDebug() << "Console Mode.\n";
std::cout << "Console Mode.\n";
//Do stuff
}
}
This is not a Qt issue, but how std::cout works. You seem to blow up your std::cout in here:
std::cout << argv[1] << std::endl;
Your issue can be reproduced even with a simple program like this:
main.pro
TEMPLATE = app
TARGET = main
CONFIG -= qt
SOURCES += main.cpp
main.cpp
#include <iostream>
int main(int /*argc*/, char **argv)
{
std::cout << argv[1] << std::endl;
std::cout << "Hello stdout!" << std::endl;
if (std::cout.bad())
std::cerr << "I/O error while reading\n";
return 0;
}
Build and Run
Success: qmake && make && ./main foo
Failure: qmake && make && ./main
In your case argv[1] is nil and so this makes std::cout not to print anything more. I would suggest to either pass an argument all the time and/or check against argc with some help usage print. The best would be to use the builtin command line parser in QtCore these days.
You could ask why? Because it is undefined behavior. You can read the details from the documentation:
basic_ostream& operator<<( std::basic_streambuf<CharT, Traits>* sb);
After constructing and checking the sentry object, checks if sb is a null pointer. If it is, executes setstate(badbit) and exits.
If you happen to have an issue with the IDE itself, for instance QtCreator, then follow these steps in case of QtCreator:
Projects -> Select a kit -> Run tab -> Run section -> Arguments
Works OK for me:
QT += core
QT -= gui
TARGET = untitled
CONFIG += console
CONFIG -= app_bundle
TEMPLATE = app
SOURCES += main.cpp
main.cpp:
#include <QCoreApplication>
#include <QTextStream>
#include <iostream>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
std::cout << "Hello World" << std::endl;
return a.exec();
}
EDIT:
#include <QCoreApplication>
#include <QTextStream>
#include <QtWidgets/QWidget>
#include <QDebug>
#include <iostream>
int main(int argc, char *argv[]) {
std::cout << "test" << std::endl; // <--- THE PROBLEM IS HERE...IF YOU TRY A SIMPLE STRING IT WORKS FINE SO THE PROBLEM IS argv[1] IS AN EMPTY STRING
//if(argc == 2 && !strcmp(argv[1],"-win")){
if(true){
//Just for this example's sake
QCoreApplication a(argc, argv);
std::cout << "Hello" << std::endl; //This is not being ouputted.
return a.exec();
}
else
{
qDebug() << "Console Mode.\n";
std::cout << "Console Mode.\n";
//Do stuff
} }
This question already has answers here:
How to deal with "%1" in the argument of QString::arg()?
(3 answers)
Closed 9 years ago.
I have tried to use the example given in the Qt4.8 documentation:
#include <QCoreApplication>
#include <QString>
#include <iostream>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QString str;
str = "%1 %2";
str.arg("%1f", "Hello"); // returns "%1f Hello"
std::cout << str.toStdString().c_str() << std::endl;
str.arg("%1f").arg("Hello"); // returns "Hellof %2"
std::cout << str.toStdString().c_str() << std::endl;
return a.exec();
}
However this outputs :
%1 %2
%1 %2
both times. I have tried this on Windows 7 and Ubuntu, using QtCreator and from the command line. I have checked I have
QMake version 2.01a
Using Qt version 4.8.1 in /usr/lib/x86_64-linux-gnu
and in Windows:
QMake version 2.01a
Using Qt version 4.7.0 in C:\qt\4.7.0\lib
I have even checked my source files for non-ascii characters, e.g. the "%" sign is correct. Please tell me why this doesn't work!
Here is the PRO file I am using:
QT += core
QT -= gui
TARGET = testarg
CONFIG += console
CONFIG -= app_bundle
TEMPLATE = app
SOURCES += main.cpp
The arg() functions do not modify the QString (if you look at the docs, these functions are const.) They return a new QString instead, which you aren't saving anywhere. If you want to modify the original string, you can do so with:
str = str.arg("%1f", "Hello");
If you want to preserve the original, just use a new QString instead:
QString tmp = str.arg("%1f", "Hello");
#include <QCoreApplication>
#include <QString>
#include <iostream>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QString str;
str = "%1 %2";
QString a = str.arg("%1f", "Hello"); // returns "%1f Hello"
std::cout << a.toStdString().c_str() << std::endl;
QString b = str.arg("%1f").arg("Hello"); // returns "Hellof %2"
std::cout << b.toStdString().c_str() << std::endl;
return a.exec();
}
note all arg overloads are const and return QString :).