Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on May 14th, 2012  |  syntax: None  |  size: 1.55 KB  |  hits: 19  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. Qt: singleton logging class get different instance accross plugins and thread
  2. #pragma once
  3.  
  4. #include <QtGui>
  5. #include <QMutex>
  6.  
  7. //! Creates a fake call, to have a cleaner design.
  8. extern void qInfo(const char* fmt);
  9.  
  10. #define QtTraceMsg  QtMsgType(6)
  11. #define QtInfoMsg   QtMsgType(7)
  12.  
  13. class MsgHandler: public QObject
  14. {
  15.     Q_OBJECT
  16.  
  17. signals:
  18.     void newMsg(QtMsgType type, const QString &msg);
  19.  
  20. public:
  21.     static MsgHandler *instance();
  22.     static void Handler(QtMsgType type, const char *msg);
  23.  
  24. private:
  25.     MsgHandler() { qRegisterMetaType<QtMsgType>("QtMsgType"); } // important
  26.     static MsgHandler* _instance;
  27. };
  28.        
  29. #include "MsgHandler.h"
  30.  
  31. MsgHandler* MsgHandler::_instance = NULL;
  32.  
  33. MsgHandler * MsgHandler::instance()
  34. {
  35.     static QMutex mutex;
  36.  
  37.     if (_instance == NULL)
  38.     {
  39.         mutex.lock();
  40.         if (_instance == NULL)
  41.             _instance = new MsgHandler;
  42.         mutex.unlock();
  43.     }
  44.  
  45.     return _instance;
  46. }
  47.  
  48. void MsgHandler::Handler(QtMsgType type, const char *msg)
  49. {
  50.     QString s = msg;
  51.     emit instance()->newMsg(type, s);
  52. }
  53.  
  54. ///////////////////////////////////////////////////////////////////////////////
  55. void qInfo(const char *msg)
  56. {
  57.     MsgHandler::instance()->Handler(QtInfoMsg, msg);
  58. }
  59.        
  60. int main(int argc, char *argv[])
  61. {
  62.     QApplication a(argc, argv);
  63.  
  64.     // Handle error messages
  65.     qInstallMsgHandler(MsgHandler::Handler);
  66. }
  67.        
  68. void MyPlugin::run()
  69. {
  70.     qWarning("Test debug"); //works fine
  71.     MsgHandler::instance()->Handler(QtInfoMsg, "info 2"); //creates a new instance!
  72.     qInfo("test info"); //also creates a new instance!
  73. }