Note that there are some explanatory texts on larger screens.

plurals
  1. POQt: singleton logging class get different instance accross plugins and thread
    text
    copied!<p>I have spent hours trying to understand why my logger class does not work. The idea is to hook existing <em>qDebug</em>, <em>qWarning</em> and <em>qFatal</em> to one of my slots and also extend the macro list with new ones (<em>qInfo</em> in this example) I tried to follow the following guidelines: <a href="https://stackoverflow.com/questions/6689370/using-a-singleton-class-across-a-qt-application-and-its-plugins">Using a Singleton Class across a Qt Application and its Plugins</a></p> <pre><code>#pragma once #include &lt;QtGui&gt; #include &lt;QMutex&gt; //! Creates a fake call, to have a cleaner design. extern void qInfo(const char* fmt); #define QtTraceMsg QtMsgType(6) #define QtInfoMsg QtMsgType(7) class MsgHandler: public QObject { Q_OBJECT signals: void newMsg(QtMsgType type, const QString &amp;msg); public: static MsgHandler *instance(); static void Handler(QtMsgType type, const char *msg); private: MsgHandler() { qRegisterMetaType&lt;QtMsgType&gt;("QtMsgType"); } // important static MsgHandler* _instance; }; </code></pre> <p>and cpp:</p> <pre><code>#include "MsgHandler.h" MsgHandler* MsgHandler::_instance = NULL; MsgHandler * MsgHandler::instance() { static QMutex mutex; if (_instance == NULL) { mutex.lock(); if (_instance == NULL) _instance = new MsgHandler; mutex.unlock(); } return _instance; } void MsgHandler::Handler(QtMsgType type, const char *msg) { QString s = msg; emit instance()-&gt;newMsg(type, s); } /////////////////////////////////////////////////////////////////////////////// void qInfo(const char *msg) { MsgHandler::instance()-&gt;Handler(QtInfoMsg, msg); } </code></pre> <p>then in the main I register my handler</p> <pre><code>int main(int argc, char *argv[]) { QApplication a(argc, argv); // Handle error messages qInstallMsgHandler(MsgHandler::Handler); } </code></pre> <p>Everything works perfectly in the main thread. But from a plugin that runs its own thread it fail:</p> <pre><code>void MyPlugin::run() { qWarning("Test debug"); //works fine MsgHandler::instance()-&gt;Handler(QtInfoMsg, "info 2"); //creates a new instance! qInfo("test info"); //also creates a new instance! } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload