コンピュータ グラフィックスでいくつかのプログラムを作成するために、Qt4 と C++ を使用しています。デバッグではなく、実行時にコンソールにいくつかの変数を出力できるようにする必要がありますがcout
、ライブラリを追加しても機能しないようです。これを行う方法はありますか?
11 に答える
に出力するのに十分な場合はstderr
、元々デバッグ用に意図されていた次のストリームを使用できます。
#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" );
QT_NO_DEBUG_OUTPUT
コメントで指摘されているように、が定義されている場合、qDebugメッセージが削除されることに注意してください
stdout が必要な場合は、次のようなものを試すことができます (Kyle Strand が指摘したように):
QTextStream& qStdOut()
{
static QTextStream ts( stdout );
return ts;
}
次に、次のように呼び出すことができます。
qStdOut() << "std out!";
への書き込みstdout
のように、アプリケーションの標準出力に書き込むものが必要な場合は、次のようにstd::cout
するだけです( CapelliC の功績によるものです)。
QTextStream(stdout) << "string to print" << endl;
一時オブジェクトの作成を避けたい場合は、ハンドルQTextStream
を返す関数を作成する以下のコメントにある Yakk の提案に従ってください。static
stdout
inline QTextStream& qStdout()
{
static QTextStream r{stdout};
return r;
}
...
foreach(QString x, strings)
qStdout() << x << endl;
flush
出力が実際に印刷されるように、定期的にストリームに記録してください。
への書き込みstderr
上記の手法は、他の出力にも使用できることに注意してください。ただし、より読みやすい書き込み方法がありますstderr
(Gozの功績と彼の回答の下のコメント):
qDebug() << "Debug Message"; // CAN BE REMOVED AT COMPILE TIME!
qWarning() << "Warning Message";
qCritical() << "Critical Error Message";
qFatal("Fatal Error Message"); // WILL KILL THE PROGRAM!
qDebug()
QT_NO_DEBUG_OUTPUT
コンパイル時にオンになっている場合は閉じられます。
(Goz はコメントで、非コンソール アプリの場合、これらは とは異なるストリームに出力される可能性があると述べていますstderr
。)
注:すべての Qt 印刷メソッドは、引数が ISO-8859-1 でエンコードされた文字列であり、終端文字が含まれていることを前提としていconst char*
\0
ます。
これをプロジェクト ファイルに追加します。
CONFIG += console
どの変数を出力しますか? QStrings を意味する場合、それらは c-Strings に変換する必要があります。試す:
std::cout << myString.toAscii().data();
プロジェクトの に移動しProperties -> Linker-> System -> SubSystem
、 に設定しConsole(/S)
ます。
stdio ライブラリを使用して stderr に出力している場合、 を呼び出すとfflush(stderr)
バッファがフラッシュされ、リアルタイムのログが取得されます。
さて、Qt の GUI から stdout にメッセージを出力する方法を説明するインターネット上のいくつかの例を調べた後、qDebug() を介してコンソールにメッセージをリダイレクトし、qInstallMessageHandler() をインストールするスタンドアロンの動作例を改良しました。コンソールは GUI と同時に表示され、必要に応じて非表示にすることができます。このコードは、プロジェクト内の既存のコードと簡単に統合できます。ここに完全なサンプルがあります。License GNU GPL v2 に準拠している限り、好きなように自由に使用してください。ある種のフォームと MainWindow を使用する必要があると思います。そうしないと、サンプルは実行されますが、強制終了するとクラッシュする可能性があります。注: 閉じるボタンまたはメニューを閉じて終了する方法はありません。これらの代替手段をテストしており、アプリケーションが時々最終的にクラッシュするためです。閉じるボタンがなければ、アプリケーションは安定し、メイン ウィンドウから閉じることができます。楽しみ!
#include "mainwindow.h"
#include <QApplication>
//GNU GPL V2, 2015-02-07
#include <QMessageBox>
#include <windows.h>
#define CONSOLE_COLUMNS 80
#define CONSOLE_ROWS 5000
#define YOURCONSOLETITLE "Your_Console_Title"
typedef struct{
CONSOLE_SCREEN_BUFFER_INFOEX conScreenBuffInfoEX;
HANDLE con_screenbuf;
HWND hwndConsole;
HMENU consoleMenu ;
QString consoleTitle;
QMessageBox mBox;
QString localMsg;
QString errorMessage;
WINBOOL errorCode;
} consoleT;
static consoleT *console;
BOOL WINAPI catchCTRL( DWORD ctrlMsg ){
if( ctrlMsg == CTRL_C_EVENT ){
HWND hwndWin = GetConsoleWindow();
ShowWindow(hwndWin,SW_FORCEMINIMIZE);
}
return TRUE;
}
void removeCloseMenu(){
int i;
for( i = 0; i < 10; i++){
console->hwndConsole = FindWindowW( NULL, console->consoleTitle.toStdWString().data());
if(console->hwndConsole != NULL)
break;
}
if( !(console->errorCode = 0) && (console->hwndConsole == NULL))
console->errorMessage += QString("\nFindWindowW error: %1 \n").arg(console->errorCode);
if( !(console->errorCode = 0) && !(console->consoleMenu = GetSystemMenu( console->hwndConsole, FALSE )) )
console->errorMessage += QString("GetSystemMenu error: %1 \n").arg(console->errorCode);
if(!(console->errorCode = DeleteMenu( console->consoleMenu, SC_CLOSE, MF_BYCOMMAND )))
console->errorMessage += QString("DeleteMenu error: %1 \n").arg(console->errorCode);
}
void initialiseConsole(){
console->conScreenBuffInfoEX.cbSize = sizeof(CONSOLE_SCREEN_BUFFER_INFOEX);
console->consoleMenu = NULL;
console->consoleTitle = YOURCONSOLETITLE;
console->con_screenbuf = INVALID_HANDLE_VALUE;
console->errorCode = 0;
console->errorMessage = "";
console->hwndConsole = NULL;
console->localMsg = "";
if(!(console->errorCode = FreeConsole()))
console->errorMessage += QString("\nFreeConsole error: %1 \n").arg(console->errorCode);
if(!(console->errorCode = AllocConsole()))
console->errorMessage += QString("\nAllocConsole error: %1 \n").arg(console->errorCode);
if( (console->errorCode = -1) && (INVALID_HANDLE_VALUE ==(console->con_screenbuf = CreateConsoleScreenBuffer( GENERIC_WRITE | GENERIC_READ,0, NULL, CONSOLE_TEXTMODE_BUFFER, NULL))))
console->errorMessage += QString("\nCreateConsoleScreenBuffer error: %1 \n").arg(console->errorCode);
if(!(console->errorCode = SetConsoleActiveScreenBuffer(console->con_screenbuf)))
console->errorMessage += QString("\nSetConsoleActiveScreenBuffer error: %1 \n").arg(console->errorCode);
if(!(console->errorCode = GetConsoleScreenBufferInfoEx(console->con_screenbuf, &console->conScreenBuffInfoEX)))
console->errorMessage += QString("\nGetConsoleScreenBufferInfoEx error: %1 \n").arg(console->errorCode);
console->conScreenBuffInfoEX.dwSize.X = CONSOLE_COLUMNS;
console->conScreenBuffInfoEX.dwSize.Y = CONSOLE_ROWS;
if(!(console->errorCode = SetConsoleScreenBufferInfoEx(console->con_screenbuf, &console->conScreenBuffInfoEX)))
console->errorMessage += QString("\nSetConsoleScreenBufferInfoEx error: %1 \n").arg(console->errorCode);
if(!(console->errorCode = SetConsoleTitleW(console->consoleTitle.toStdWString().data())))
console->errorMessage += QString("SetConsoleTitle error: %1 \n").arg(console->errorCode);
SetConsoleCtrlHandler(NULL, FALSE);
SetConsoleCtrlHandler(catchCTRL, TRUE);
removeCloseMenu();
if(console->errorMessage.length() > 0){
console->mBox.setText(console->errorMessage);
console->mBox.show();
}
}
void messageHandler(QtMsgType type, const QMessageLogContext &context, const QString &msg){
if((console->con_screenbuf != INVALID_HANDLE_VALUE)){
switch (type) {
case QtDebugMsg:
console->localMsg = console->errorMessage + "Debug: " + msg;
WriteConsoleW(console->con_screenbuf, console->localMsg.toStdWString().data(), console->localMsg.toStdWString().length(), NULL, NULL );
WriteConsoleA(console->con_screenbuf, "\n--\n", 4, NULL, NULL );
break;
case QtWarningMsg:
console->localMsg = console->errorMessage + "Warning: " + msg;
WriteConsoleW(console->con_screenbuf, console->localMsg.toStdWString().data(), console->localMsg.toStdWString().length() , NULL, NULL );
WriteConsoleA(console->con_screenbuf, "\n--\n", 4, NULL, NULL );
break;
case QtCriticalMsg:
console->localMsg = console->errorMessage + "Critical: " + msg;
WriteConsoleW(console->con_screenbuf, console->localMsg.toStdWString().data(), console->localMsg.toStdWString().length(), NULL, NULL );
WriteConsoleA(console->con_screenbuf, "\n--\n", 4, NULL, NULL );
break;
case QtFatalMsg:
console->localMsg = console->errorMessage + "Fatal: " + msg;
WriteConsoleW(console->con_screenbuf, console->localMsg.toStdWString().data(), console->localMsg.toStdWString().length(), NULL, NULL );
WriteConsoleA(console->con_screenbuf, "\n--\n", 4, NULL, NULL );
abort();
}
}
}
int main(int argc, char *argv[])
{
qInstallMessageHandler(messageHandler);
QApplication a(argc, argv);
console = new consoleT();
initialiseConsole();
qDebug() << "Hello World!";
MainWindow w;
w.show();
return a.exec();
}