How to use terminal commands on qt - qt

I am QT for a project and I want to compile and run few C++ codes on QT. I have written the following code to compile a C++ file. But I don't know how to check if the program was compiled properly. If once the program has compiled, how do I run it in a terminal?
The revised code:
void MainWindow::on_actionComplile_triggered()
{
QProcess compile;
compile.setWorkingDirectory("/home");
compile.setReadChannel(QProcess::StandardOutput);
compile.setProcessChannelMode(QProcess::MergedChannels);
QTextStream out(stdout);
compile.start("gnome-terminal");
compile.write("ls"); //these lines do not get printed.
compile.waitForReadyRead();
compile.waitForFinished(-1);
QByteArray msg = compile.readAll();
out << msg.data() << endl;
}

I Found the Solution:
void MainWindow::on_actionComplile_triggered()
{
QProcess compile;
compile.setWorkingDirectory("/home/royal");
compile.setReadChannel(QProcess::StandardOutput);
compile.setProcessChannelMode(QProcess::MergedChannels);
QTextStream out(stdout);
compile.start("g++",QStringList() << "tes.cpp" << "-o" << "test");
compile.waitForFinished(-1);
QByteArray msg = compile.readAllStandardOutput();
if(msg.isEmpty())
{
qDebug() << "Successful";
}
else qDebug() << "Failed";
}

Related

QProcess output with adb always empty

I am starting a QProcess to get e.g. the return of "adb devices".
There is no error and always an empty response. I have adb in my system env on Windows and the command runs fine on cmd.
Am I doing anythin wrong or is there another way to run adb commands in QT?
class ADBInfo: public QObject {
public:
void start(){
process = new QProcess( this );
process->start("adb.exe devices");
process->waitForFinished(-1);
qDebug() << "output: " << process->readAll();
qDebug() << "error: " << process->readAllStandardError();
}
private:
QProcess *process;
};
here is the correct way
QString mainwindow::cmd(const QString &command)
{
qDebug () << "command = "+command;
QProcess P2;
P2.start(command);
P2.waitForFinished(-1);
P2.setReadChannel(QProcess::StandardOutput);
QTextStream reade2(&P2);
QString line2,line,Out;
while (reade2.readLineInto(&line2))
Out.append(line2 +'\n');
P2.setReadChannel(QProcess::StandardError);
QTextStream reader(&P2);
while (reader.readLineInto(&line))
Out.append(line +'\n');
P2.close();
return Out.trimmed();
}
when you need to excute command
QString Result = cmd("adb devices")

Receipt printer feeds paper instead of printing text

I am working on test application for printing in Ubuntu 14.04.3 LTS with CUPS 1.7.2 and Qt 5.5.1 Opensource 64bit. I've added printer with its driver in CUPS and test page is printed ok. Now, my app consists of QTextEdit and QPushButton, whose pressed() signal triggers following slot:
void UeCentralWidget::ueSendTextToPrinter()
{
// QStringList availablePrintersNames=QPrinterInfo::availablePrinterNames();
// for(int indexPrinterName=0; indexPrinterName<availablePrintersNames.size(); indexPrinterName++)
// {
// qDebug() << Q_FUNC_INFO
// << availablePrintersNames.at(indexPrinterName);
// } // for
qDebug() << Q_FUNC_INFO
<< "Text to print: "
<< this->uePrinterTextEditor()->document()->toPlainText();
QList<QPrinterInfo> availablePrinters=QPrinterInfo::availablePrinters();
for(int indexPrinter=0; indexPrinter<availablePrinters.size(); indexPrinter++)
{
// qDebug() << Q_FUNC_INFO
// << availablePrinters.at(indexPrinter).makeAndModel();
if(availablePrinters.at(indexPrinter).makeAndModel().contains("POS58"))
{
qDebug() << Q_FUNC_INFO
<< "Printer found";
QPrinter printer(availablePrinters.at(indexPrinter));
qDebug() << Q_FUNC_INFO
<< printer.pageLayout().fullRect();
QPainter printerPainter(&printer);
qDebug() << Q_FUNC_INFO
<< printerPainter.fontInfo().family()
<< printerPainter.fontInfo().pixelSize()
<< printerPainter.fontInfo().pointSize();
if(printerPainter.begin(&printer))
{
printerPainter.drawText(100,
100,
this->uePrinterTextEditor()->document()->toPlainText());
}
printerPainter.end();
} // if
} // for
}
When this slot executes, printer job is added to CUPS queue, which means printer is found, however, printer just feeds printer and no text is printed. What am I still missing?
You don't need the printerPainter.begin(&printer) or the printerPainter.end().
I don't know why that fixes it for you, but if I was to guess it might be because explicitly calling printerPainter.end() prematurely completes the paint operation before the drawing is actually done.

Qt - Writing a file with QTextStream adds empty new lines to the text

I'm using the following code to write some text to a file:
QFile caFile(outputFolder + "file.extension");
caFile.open(QIODevice::WriteOnly | QIODevice::Text);
if(!caFile.isOpen()){
qDebug() << "- Error, unable to open" << "outputFilename" << "for output";
}
QTextStream outStream(&caFile);
outStream << "First Line\nSecond Line\nThird Line";
caFile.close();
It's working like a charm, but with a little problem ..
The text file should look like this:
First Line
Second Line
Third Line
But instead, it looks like this:
First Line
Second Line
Third Line
What's the problem here?
It works for me like a charm.
input.txt
DA3MTkyMjE0NDdaFw0xODA2MDYyMjE0NDdaMDcxEzARBgNVBAMMCnVqY2E2bjku
anAxEzARBgNVBAoMCnZtamMgMm5vYjMxCzAJBgNVBAYTAlVTMIIBIjANBgkqhkiG
9w0BAQEFAAOCAQ8AMIIBCgKCAQEAz0+a0BEJEkPwNq7BEplV81+++wzonVAWWcqe
main.cpp
#include <QTextStream>
#include <QFile>
#include <QDebug>
#include <QByteArray>
int main()
{
QFile inFile("input.txt");
inFile.open(QIODevice::ReadOnly | QIODevice::Text);
QByteArray inputData = inFile.readAll();
QFile caFile("output.txt");
caFile.open(QIODevice::WriteOnly | QIODevice::Text);
if(!caFile.isOpen()){
qDebug() << "- Error, unable to open" << "outputFilename" << "for output";
}
QTextStream outStream(&caFile);
outStream << inputData;
caFile.close();
return 0;
}
main.pro
TEMPLATE = app
TARGET = main
QT = core
SOURCES += main.cpp
Build and Run
qmake && make && ./main
output.txt
DA3MTkyMjE0NDdaFw0xODA2MDYyMjE0NDdaMDcxEzARBgNVBAMMCnVqY2E2bjku
anAxEzARBgNVBAoMCnZtamMgMm5vYjMxCzAJBgNVBAYTAlVTMIIBIjANBgkqhkiG
9w0BAQEFAAOCAQ8AMIIBCgKCAQEAz0+a0BEJEkPwNq7BEplV81+++wzonVAWWcqe
QString filename = "";//file adding path
QFile file(filename);
file.open(QIODevice::ReadWrite);
QTextStream stream(&file);
stream << "abc\nxyz" << endl;
file.close();
output:abc
xyz

QFile doesn’t create the file

I am writing a simple program. The program has 2 QStrings set with following variables: path and name of file, there is a 3rd QString which I later on use to put the result of the append of the first 2 QString together in. What I want to do is append the 2 QStrings and put them in the appendAll QString, and then send the appendAll QString to the QFile variable constructor. Now when I do that, it prints "Failed to Create File", this is the code I used:
#include <QString>
#include <QTextStream>
#include <QFile>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QTextStream output(stdout);
QString location = "/home/mahmoud/Destkop";
QString name = "mahmoud.txt";
QString appendAll;
if( !location.endsWith("/") )
{
location.append("/");
}
appendAll = location.append(name);
output << appendAll << endl;
QFile myFile(appendAll);
if(myFile.open(QIODevice::WriteOnly | QIODevice::Text ))
{
output << "File Has Been Created" << endl;
}
else
{
output << "Failed to Create File" << endl;
}
QTextStream writeToFile(&myFile);
writeToFile << "Hello World" << endl;
myFile.close();
return a.exec();
}
But when I type the string directly into the QFile variable constructor in the same program it prints, "File Has Been Created" and I find it on my desktop, the below code works fine:
QFile myFile("/home/mahmoud/Desktop/mahmoud.txt");
if(myFile.open(QIODevice::WriteOnly | QIODevice::Text ))
{
output << "File Has Been Created" << endl;
}
else
{
output << "Failed to Create File" << endl;
}
I want to be able to already have QStrings and append them and send them to the QFile variable constructor, any suggestions on how to solve my problem? Thank You
Do not hard-code this filesystem location. Instead, in Qt4 you should be using QDesktopServices:
QString location =
QDesktopServices::storageLocation(QDesktopServices::DesktopLocation);
In Qt5, it's QStandardPaths:
QString location =
QStandardPaths::writableLocation(QStandardPaths::DesktopLocation);
This is important because /home/username/Desktop is not guaranteed to be the user's Desktop folder.
There is typing error in your code: Destkop should be Desktop. Qt can't create file in non-existent directory.

QProcess exits before complete

I've got some code that starts mencoder in a QProcess, converts a video while displaying a progress bar, then exits. The problem is, mencoder always exits before it's actually finished. The loop runs through a few times, and then closes. If I comment out the line that updates the progress bar (progress.setValue()), mencoder runs to completion and exits happily.
Been at this for a day, and can't figure it out! Also, I should mention I'm on a Mac.
Any ideas?
Thanks
Marlon
void MainWindow::convertVideo()
{
QString input_filename = "/var/input.avi";
QString output_filename = "/var/output.264";
QStringList arguments;
arguments << input_filename << "-nosound" << "-of" << "rawvideo" << "-ofps" << "30" << "-vf" << "harddup" << "-ovc" << "x264" << "-x264encopts" << "bframes=0" << "-o" << output_filename;
QProcess* myProcess = new QProcess(this);
myProcess->setReadChannel(QProcess::StandardOutput);
myProcess->start("/opt/local/bin/mencoder", arguments);
QString output_string;
QStringList output_pieces;
QProgressDialog progress("Converting video...", "Abort", 0, 100, this);
progress.setWindowModality(Qt::WindowModal);
progress.setValue(0);
progress.show();
while(myProcess->state() != QProcess::NotRunning)
{
output_string = myProcess->readAllStandardOutput();
output_pieces = output_string.split(" ");
QStringList width_string_list = output_pieces.filter("%)");
if(width_string_list.length() > 0)
{
width_string_list = width_string_list[width_string_list.length() - 1].split("(");
if(width_string_list.length() > 1)
{
width_string_list = width_string_list[1].split("%");
}
else
{
width_string_list = width_string_list[0].split("%");
}
progress.setValue(width_string_list[0].toInt());
qDebug() << width_string_list[0].toInt();
}
myProcess->waitForReadyRead();
}
return;
}
I think the QProcess timeouts before it finishes its job. Adding a myProcess->waitForFinished(-1) might help. Then your process wont timeout.

Resources