qInstallMsgHandler在Qt中注册日志函数时出错

qInstallMsgHandler在Qt中注册日志函数时出错,qt,qt4,Qt,Qt4,我正在设计Qt日志窗口,所以我使用qInstallMsgHandler()函数将所有调试、关键和警告消息记录到QTableWidget上(在下面的代码中,我还没有实现)。我做的如下 int main(int argc, char *argv[]) { qInstallMsgHandler(MainWindow::logMessage); //qInstallMsgHandler(&MainWindow::logMessage); //I tried this also

我正在设计Qt日志窗口,所以我使用qInstallMsgHandler()函数将所有调试、关键和警告消息记录到QTableWidget上(在下面的代码中,我还没有实现)。我做的如下

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();
}
当我编译这段代码时,我发现了下面的错误

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);
如果有人遇到过这个问题,请告诉我

注意:如果我更改了void main window::logMessage(QtMsgType类型,const char*msg);此函数转换为静态函数,工作正常

(但是如果这个函数是静态的,我不能创建QTableWidgetItem并将它们添加到tableWidget,所以我希望这个函数是非静态的)

我正在Windows7上使用Qt4.8.6


提前谢谢

在MainWindow中定义一个静态变量MainWindow,该变量允许您从静态函数访问MainWindow实例,例如

static MainWindow *_this;
在构造函数中设置此变量:

MainWindow::MainWindow()
{
   _this = this;
}
创建一个具有相同签名的静态函数,并在
qInstallMsgHandler
中注册。此函数将仅使用static\u This重定向到not static函数:

static void logMessageHandle(QtMsgType type, const char *msg)
{
   if(_this)
      _this->logMessage(type,msg);
}

希望这有帮助。

这正是问题所在——您必须在那里使用自由函数,而不是成员函数。一个选项是使用
std::bind
捕获实例,但随后需要在创建
main窗口后移动
qInstallMsgHandler
调用。另一种方法是使您的
MainWindow
实例成为真正的单例实例,即通过
MainWindow::instance()
或类似的方法进行访问。或者使用C++11 lambda,它可以捕获MainWindow ptr。
static void logMessageHandle(QtMsgType type, const char *msg)
{
   if(_this)
      _this->logMessage(type,msg);
}