qDebug Qt console application to output to Qt Creator application output

后端 未结 2 1989
南方客
南方客 2021-02-09 07:17

How do I use qDebug in a Qt console application to output to the Qt Creator \"application output\" window? Currently qDebug writes to the console window which interferes with th

2条回答
  •  不要未来只要你来
    2021-02-09 07:52

    To redirect QDebug to multiple places, you might have to write some code, maybe like this:

    QList messageHandlers_;
    
    static void messageDispatcher(QtMsgType type, const char *msg)
    {
      foreach (QtMsgHandler callback, ::messageHandlers_)
        callback(type, msg);
    }
    
    static void messageLogger(QtMsgType type, const char *msg)
    {
      QString output;
      switch (type) {
      case QtDebugMsg:    output = QString("mesage: %1\n").arg(msg); break;
      case QtWarningMsg:  output = QString("warning: %1\n").arg(msg); break;
      case QtCriticalMsg: output = QString("critical: %1\n").arg(msg); break;
      case QtFatalMsg:    output = QString("fatal: %1\n").arg(msg); break;
      default: return;
      }
    
      QFile file("log.txt");
      if (file.open(QIODevice::WriteOnly | QIODevice::Append))
        QTextStream(&file) << output;
    }
    
    int main()
    {
      ...
      ::messageHandlers_.append(messageLogger)
      qInstallMsgHandler(messageDispatcher);
      ...
    }
    

提交回复
热议问题