代码之家  ›  专栏  ›  技术社区  ›  Rob

Qt GUI应用程序中的控制台输出?

  •  46
  • Rob  · 技术社区  · 14 年前

    我有一个运行在Windows上的Qt GUI应用程序,它允许传递命令行选项,在某些情况下,我希望向控制台输出一条消息,然后退出,例如:

    int main(int argc, char *argv[])
    {
      QApplication a(argc, argv);
    
      if (someCommandLineParam)
      {
        std::cout << "Hello, world!";
        return 0;
      }
    
      MainWindow w;
      w.show();
    
      return a.exec();
    }
    

    16 回复  |  直到 9 年前
        1
  •  47
  •   David Dibben    14 年前

    Windows并不真正支持双模应用程序。

    要查看控制台输出,您需要创建一个控制台应用程序

    CONFIG += console
    

    一个想法可能是创建第二个小应用程序,它是一个控制台应用程序并提供输出。这可以叫第二个来做这项工作。

        2
  •  27
  •   patstew    8 年前

    添加:

    #ifdef _WIN32
    if (AttachConsole(ATTACH_PARENT_PROCESS)) {
        freopen("CONOUT$", "w", stdout);
        freopen("CONOUT$", "w", stderr);
    }
    #endif
    

    main()

    if (AttachConsole(ATTACH_PARENT_PROCESS) || AllocConsole())
    
        3
  •  7
  •   Gank    11 年前
    void Console()
    {
        AllocConsole();
        FILE *pFileCon = NULL;
        pFileCon = freopen("CONOUT$", "w", stdout);
    
        COORD coordInfo;
        coordInfo.X = 130;
        coordInfo.Y = 9000;
    
        SetConsoleScreenBufferSize(GetStdHandle(STD_OUTPUT_HANDLE), coordInfo);
        SetConsoleMode(GetStdHandle(STD_OUTPUT_HANDLE),ENABLE_QUICK_EDIT_MODE| ENABLE_EXTENDED_FLAGS);
    }
    
    int main(int argc, char *argv[])
    {
        Console();
        std::cout<<"start@@";
        qDebug()<<"start!";
    

    你不能像其他人说的那样使用std::cout,我的方法是完美的,即使有些代码不能包含“qdebug”!

        4
  •  5
  •   orftz user727395    14 年前

    使用时无法将消息输出到控制台 QT += gui .

    fprintf(stderr, ...)

    使用 QMessageBox 而是显示信息。

        5
  •  4
  •   Seb    13 年前

    哦,你可以在使用 QT += gui CONFIG += console .

    你需要 printf("foo bar") cout << "foo bar" 不起作用

        6
  •  4
  •   Pixtar    7 年前

    所以我试了一下 . 我花了很多时间 几个小时 要有一个良好的工作解决方案,不会在链的某个地方产生任何问题:

    #include "mainwindow.h"
    
    #include <QApplication>
    
    #include <windows.h>
    #include <stdio.h>
    #include <iostream>
    
    //
    // Add to project file:
    // CONFIG += console
    //
    
    int main( int argc, char *argv[] )
    {
        if( argc < 2 )
        {
        #if defined( Q_OS_WIN )
            ::ShowWindow( ::GetConsoleWindow(), SW_HIDE ); //hide console window
        #endif
            QApplication a( argc, argv );
            MainWindow *w = new MainWindow;
            w->show();
            int e = a.exec();
            delete w; //needed to execute deconstructor
            exit( e ); //needed to exit the hidden console
            return e;
        }
        else
        {
            QCoreApplication a( argc, argv );
            std::string g;
            std::cout << "Enter name: ";
            std::cin >> g;
            std::cout << "Name is: " << g << std::endl;
            exit( 0 );
            return a.exec();
        }
    }
    


    没有 “CONFIG+=console”,但是您需要重定向流并自己创建控制台:

    #ifdef _WIN32
    if (AttachConsole(ATTACH_PARENT_PROCESS) || AllocConsole()){
        freopen("CONOUT$", "w", stdout);
        freopen("CONOUT$", "w", stderr);
        freopen("CONIN$", "r", stdin);
    }
    #endif
    

    只有通过调试器启动它,否则所有输入也都指向系统。意思是,如果您通过std::cin键入一个名称,系统将尝试以命令的形式执行该名称((非常奇怪)

    另外两个警告 对于这种尝试,你不能使用::FreeConsole()它不会关闭它,如果你通过控制台启动它,应用程序也不会关闭。



    最后是一个 Qt help section in QApplication 关于这个话题。我在那里用一个应用程序尝试了这个例子 ,它在一个无休止的循环中阻塞了,GUI将无法呈现,或者它只是崩溃了:

    QCoreApplication* createApplication(int &argc, char *argv[])
    {
        for (int i = 1; i < argc; ++i)
            if (!qstrcmp(argv[i], "-no-gui"))
                return new QCoreApplication(argc, argv);
        return new QApplication(argc, argv);
    }
    
    int main(int argc, char* argv[])
    {
        QScopedPointer<QCoreApplication> app(createApplication(argc, argv));
    
        if (qobject_cast<QApplication *>(app.data())) {
           // start GUI version...
        } else {
           // start non-GUI version...
        }
    
        return app->exec();
    }
    


    因此,如果您使用的是Windows和Qt,只需使用console选项,如果需要GUI,请隐藏控制台并通过exit关闭它。

        7
  •  2
  •   Josh    12 年前
        8
  •  1
  •   mosg    14 年前

    我在我的项目中使用了下面的标题。希望有帮助。

    #ifndef __DEBUG__H
    #define __DEBUG__H
    
    #include <QtGui>    
    
    static void myMessageOutput(bool debug, QtMsgType type, const QString & msg) {
    
        if (!debug) return;
    
        QDateTime dateTime = QDateTime::currentDateTime();
        QString dateString = dateTime.toString("yyyy.MM.dd hh:mm:ss:zzz");
    
        switch (type) {
    
            case QtDebugMsg:
                fprintf(stderr, "Debug: %s\n", msg.toAscii().data());
                break;
            case QtWarningMsg:
                fprintf(stderr, "Warning: %s\n", msg.toAscii().data());
                break;
            case QtCriticalMsg:
                fprintf(stderr, "Critical: %s\n", msg.toAscii().data());
                break;
            case QtFatalMsg:
                fprintf(stderr, "Fatal: %s\n", msg.toAscii().data());
                abort();
        }
    }
    
    #endif
    

    附言:你可以加上 dateString 如果你想在将来输出。

        9
  •  0
  •   rubenvb    14 年前

    首先,为什么需要在发布模式构建中输出到控制台?当有一个图形用户界面时,没有人会想到去看那里。。。

    第二,qDebug很花哨:)

    第三,可以尝试添加 console .pro CONFIG

        10
  •  0
  •   Derick Schoonbee    14 年前

    在你的.pro中添加

    CONFIG          += console
    
        11
  •  0
  •   Tech1337    10 年前

    这可能是对其他答案的疏忽,也可能是用户确实需要控制台输出的要求,但对我来说,显而易见的答案是创建一个可以显示或隐藏的辅助窗口(带有复选框或按钮),通过将文本行附加到文本框小部件并将其用作控制台来显示所有消息?

    • 一个简单的解决方案(提供一个简单的日志)。
    • 能够创建多个控制台(如果有多个线程等)。
    • 从本地控制台输出到通过网络向客户机发送日志是一个非常简单的改变。

    希望这能让你深思熟虑,虽然我还没有资格假设你应该怎么做,但我可以想象,只要我们中的任何一个人稍加搜索/阅读,这是非常可以实现的!

        12
  •  0
  •   user5157912 user5157912    9 年前

    我在Qt5的控制台应用程序中遇到了类似的问题: 如果我从Qt Creator启动应用程序,输出文本是可见的, 如果我打开cmd.exe并在那里启动相同的应用程序,就看不到任何输出。

    我通过复制解决了这个问题 应用程序可执行文件所在的目录。

    #include <QCoreApplication>
    #include <QDebug>
    
    int main(int argc, char *argv[])
    {
        int x=343;
        QString str("Hello World");
        qDebug()<< str << x<<"lalalaa";
    
        QTextStream out(stdout);
        out << "aldfjals alsdfajs...";
    }
    
        13
  •  0
  •   David Athersych    9 年前

    请原谅这个蹩脚的例子-它代表了大约30分钟的修补。

    #include "mainwindow.h"
    #include <QTextStream>
    #include <QCoreApplication>
    #include <QApplication>
    #include <QWidget>
    #include <windows.h>
    
    QT_USE_NAMESPACE
    
    int main(int argc, char *argv[])
    {
        if (argc > 1)   {
            // User has specified command-line arguments
            QCoreApplication a(argc, argv);
            QTextStream  out(stdout);
            int     i;
    
            ShowWindow (GetConsoleWindow(),SW_NORMAL);
            for (i=1; i<argc; i++)
                 out << i << ':' << argv [i] << endl;
            out << endl << "Hello, World" << endl;
            out << "Application Directory Path:" << a.applicationDirPath() << endl;
            out << "Application File Path:" << a.applicationFilePath() << endl;
            MessageBox (0,(LPCWSTR)"Continue?",(LPCWSTR)"Silly Question",MB_YESNO);
            return 0;
        } else  {
            QApplication a(argc, argv);
            MainWindow w;
    
            w.setWindowTitle("Simple example");
            w.show();
            return a.exec();
        }
    }
    
        14
  •  0
  •   lemon339    8 年前

    CONFIG   += console
    

    真的很管用。只有明确告诉QtCreator在项目上执行qmake(右键单击项目)并更改源文件中的某些内容,然后重新生成,它才能工作。否则编译将被跳过,您仍然无法在命令行上看到输出。 现在我的程序在GUI和cmd行模式下工作。

        15
  •  0
  •   Henrique Mageste    5 年前

    下面是从cmd.exe运行powershell并将我的\u exec.exe输出重定向到控制台和output.txt文件的示例:

    powershell ".\my_exec.exe | tee output.txt"
    
        16
  •  -1
  •   loyola    8 年前

    容易的

    创建新项目。转到文件->新建文件或项目-->其他项目-->空项目

    第二步: 使用以下代码。

    在.pro文件中

    QT +=widgets
    CONFIG += console
    TARGET = minimal
    SOURCES += \ main.cpp
    

    创建main.cpp并复制下面的代码。

    #include <QApplication>
    #include <QtCore>
    
    using namespace  std;
    
    QTextStream in(stdin);
    QTextStream out(stdout);
    
    int main(int argc, char *argv[]){
    QApplication app(argc,argv);
    qDebug() << "Please enter some text over here: " << endl;
    out.flush();
    QString input;
    input = in.readLine();
    out << "The input is " << input  << endl;
    return app.exec();
    }
    

    快跑吧

    如果您想让程序在某些条件下获得多个输入。然后通过Main.cpp中的以下代码

    #include <QApplication>
    #include <QtCore>
    
    using namespace  std;
    
    QTextStream in(stdin);
    QTextStream out(stdout);
    
    int main(int argc, char *argv[]){
        QApplication app(argc,argv);
        qDebug() << "Please enter some text over here: " << endl;
        out.flush();
        QString input;
        do{
            input = in.readLine();
            if(input.size()==6){
                out << "The input is " << input  << endl;   
            }
            else
            {
                qDebug("Not the exact input man");
            }
        }while(!input.size()==0);
    
        qDebug(" WE ARE AT THE END");
    
        // endif
        return app.exec();
    } // end main
    

    很好的一天,

        17
  •  -3
  •   Piotr Duda    14 年前

    std::cout << "Hello, world!"<<std::endl;
    

    要获得更多基于Qt的日志记录,可以尝试使用qDebug。