Search code examples
c++qtstylesheet

How do I capture errors printed when calling setStyleSheet() in Qt C++?


For example:

mywidget->setStyleSheet("QSlider::groove:horizontal { hight: 200px; }");

prints this to the console in Qt Creator:

Unknown property hight

It is obvious to the programmer in this case where the error is, but what if it is a different person working on the stylesheet as an external file? What if that person doesn't have access to Qt Creator to see the message? It would be good to capture the message and display it for the user in some application-specific way. Is this a simple task of redirecting stderr? Or is it more Qt-specific? I would appreciate any examples. Thanks.


Solution

  • You can use qInstallMsgHandler() to capture the Qt's error messages. Check the documentation here : http://doc.qt.io/archives/qt-4.7/qtglobal.html

    I c/c the example from the doc. You can easily modify it to show these messages in the user interface.

    void myMessageOutput(QtMsgType type, const char *msg)
     {
         switch (type) {
         case QtDebugMsg:
             fprintf(stderr, "Debug: %s\n", msg);
             break;
         case QtWarningMsg:
             fprintf(stderr, "Warning: %s\n", msg);
             break;
         case QtCriticalMsg:
             fprintf(stderr, "Critical: %s\n", msg);
             break;
         case QtFatalMsg:
             fprintf(stderr, "Fatal: %s\n", msg);
             abort();
         }
     }
    
     int main(int argc, char **argv)
     {
         qInstallMsgHandler(myMessageOutput);
         QApplication app(argc, argv);
         ...
         return app.exec();
     }
    

    Note: in Qt 5.0 it is deprecated. Use qInstallMessageHandler() instead.