PDA

View Full Version : qInstallMsgHandler() error while registering non static function



DURGAPRASAD NEELAM
24th May 2015, 21:30
I am designing Qt log window, So I am using qInstallMsgHandler() function to log all the debug, critical & warning messages on to QTableWidget (in below code I have not implemented It yet). I did as below


int main(int argc, char *argv[])
{
qInstallMsgHandler(MainWindow::logMessage);
//qInstallMsgHandler(&MainWindow::logMessage); //I tried this also

QApplication a(argc, argv);
MainWindow w;
qDebug() << "info message";
qWarning() << "warning message";
qCritical() << "critical message";
w.show();

return a.exec();
}


MainWindow:


MainWindow::MainWindow(QWidget *parent) :QMainWindow(parent),ui(new Ui::MainWindow)
{
ui->setupUi(this);
}

MainWindow::~MainWindow()
{
delete ui;
}

void MainWindow::logMessage(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();
}
}


When I compile this code, I am getting below error


main.cpp:27: error: cannot convert 'void (MainWindow::*)(QtMsgType, const char*)' to 'QtMsgHandler {aka void (*)(QtMsgType, const char*)}' for argument '1' to 'void (* qInstallMsgHandler(QtMsgHandler))(QtMsgType, const char*)'
qInstallMsgHandler(MainWindow::logMessage);


Note : If I changed void MainWindow::logMessage(QtMsgType type, const char *msg); this function to static function then it is working fine.
(But if this function is static, I can not create QTableWidgetItem and add them to tableWidget so I want this function to be non static).

And one more issue i am having here, When I use static function, all the messages are printing after I close my application only.

Please let me know What is the issue.

I am using Qt4.8.6 on Windows7

Thanks In Advance.

jefftee
24th May 2015, 22:44
The QtMsgHandler function does not take a "this" pointer, which is why you can't use a non-static member function. Either make it a non-member function or a static member function.

Try adding a fflush(stderr) at the end of your logging function, which will ensure your messages are not buffered and shown immediately after they are written.