How to print to console when using Qt
If it is good enough to print to stderr
, you can use the following streams originally intended for debugging:
#include<QDebug>
//qInfo is qt5.5+ only.
qInfo() << "C++ Style Info Message";
qInfo( "C Style Info Message" );
qDebug() << "C++ Style Debug Message";
qDebug( "C Style Debug Message" );
qWarning() << "C++ Style Warning Message";
qWarning( "C Style Warning Message" );
qCritical() << "C++ Style Critical Error Message";
qCritical( "C Style Critical Error Message" );
// qFatal does not have a C++ style method.
qFatal( "C Style Fatal Error Message" );
Though as pointed out in the comments, bear in mind qDebug messages are removed if QT_NO_DEBUG_OUTPUT
is defined
If you need stdout you could try something like this (as Kyle Strand has pointed out):
QTextStream& qStdOut()
{
static QTextStream ts( stdout );
return ts;
}
You could then call as follows:
qStdOut() << "std out!";
qt printing to terminal
To write to stdout, you should add this CONFIG += console
to your project file config and use cout
of printf
for your liking. qDebug
prints by default to stderr
. Check this topic for more info - How to print to console when using Qt
Console output in a Qt GUI app?
Windows does not really support dual mode applications.
To see console output you need to create a console application
CONFIG += console
However, if you double click on the program to start the GUI mode version then you will get a console window appearing, which is probably not what you want. To prevent the console window appearing you have to create a GUI mode application in which case you get no output in the console.
One idea may be to create a second small application which is a console application and provides the output. This can call the second one to do the work.
Or you could put all the functionality in a DLL then create two versions of the .exe file which have very simple main functions which call into the DLL. One is for the GUI and one is for the console.
QJSEngine: print to console
The print function is not implemented in QJSEngine. You will have to implement it yourself. Luckily you can write QObjects and make them available in your script. (See section "QObject Integration" at http://doc.qt.io/qt-5/qjsengine.html)
Here's how i've done it:
Create a class JSConsole inheriting from QObject:
Your own console class
jsconsole.h
#ifndef JSCONSOLE_H
#define JSCONSOLE_H
#include <QObject>
class JSConsole : public QObject
{
Q_OBJECT
public:
explicit JSConsole(QObject *parent = 0);
signals:
public slots:
void log(QString msg);
};
#endif // JSCONSOLE_H
jsconsole.cpp
#include "jsconsole.h"
#include <QDebug>
JSConsole::JSConsole(QObject *parent) :
QObject(parent)
{
}
void JSConsole::log(QString msg)
{
qDebug() << "jsConsole: "<< msg;
}
Using it
Now you create a proxy object in the js engine by using QJSEngine.newQObject.
After that you add it to your global object and use it.
QJSEngine engine;
JSConsole console;
QJSValue consoleObj = engine.newQObject(&console);
engine.globalObject().setProperty("console", consoleObj);
QJSValue result = engine.evaluate("console.log('test');");
Error logging
I've searched a long time for errors in my c++ code, when i just made a spelling error in my js file. The following snippet would have helped avoid that.
if (result.isError())
{
qDebug() << "result: " << result.property("lineNumber").toInt() << ":" << result.toString();
}
PS: First post after years of lurking. I've read tips on writing great answers but if I've made some mistakes/bad things please tell me.
May the code be with you
Printing Output from Console Live To QTextEdit
Do not use subprocess.Popen()
since it is blocking and it only gives you the result at the end of the execution, instead use QProcess
:
import sys
from PyQt5 import QtCore, QtWidgets
class Widget(QtWidgets.QWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.process = QtCore.QProcess(self)
self.process.setProgram("dirb")
self.process.setProcessChannelMode(QtCore.QProcess.MergedChannels)
self.lineedit = QtWidgets.QLineEdit("http://webscantest.com")
self.button = QtWidgets.QPushButton("Start")
self.textedit = QtWidgets.QTextEdit(readOnly=True)
lay = QtWidgets.QGridLayout(self)
lay.addWidget(self.lineedit, 0, 0)
lay.addWidget(self.button, 0, 1)
lay.addWidget(self.textedit, 1, 0, 1, 2)
self.button.clicked.connect(self.on_clicked)
self.process.readyReadStandardOutput.connect(self.on_readyReadStandardOutput)
self.process.finished.connect(self.on_finished)
@QtCore.pyqtSlot()
def on_clicked(self):
if self.button.text() == "Start":
self.textedit.clear()
self.process.setArguments([self.lineedit.text()])
self.process.start()
self.button.setText("Stop")
elif self.button.text() == "Stop":
self.process.kill()
@QtCore.pyqtSlot()
def on_readyReadStandardOutput(self):
text = self.process.readAllStandardOutput().data().decode()
self.textedit.append(text)
@QtCore.pyqtSlot()
def on_finished(self):
self.button.setText("Start")
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
w = Widget()
w.show()
sys.exit(app.exec_())
View C++ output in terminal when executing Qt application (macOS)
To see the program's stdout
output in Terminal, you can run it instead like this:
./application.app/Contents/MacOS/application
Related Topics
Raspberry Pi Refusing Connection to Bottle Server
Undefined Reference to 'Pthread_Init' When Using -Lpthread Flag:
How to Identify the User Who Owns a Process from /Proc/Pid
Cuda 5.0: Replacement for Cutil.H
How to Split Flv File by Size Using Ffmpeg or Mencoder or Smth Else
Average of Multiple Files Without Considering Missing Values
Will Process Lost Wake-Up Chance in a Preemptive Kernel
Why a Linux Redirect Truncates the File
Mongod Does Not Start (Mongod.Service: Failed with Result 'Signal')
How to Read Input from the Terminal Using /Dev/Stdin and Read.Csv()
Bash -Eq and ==, What's the Diff
How to Configure Acpi *.Asl for a Virtual Mdio-Gpio Device Connected to a I2C Gpio Expander
Run Bash Script in Raspberry Pi via Ifttt
Replace Parentheses and Spaces in Filenames with Underscore
Why This Bash Function Prints Only First Word of Whole String
How to Change the Permissions in Openshift Container Platform