How to show message from external library callback/staic function in QTextEdit (emit signal from static function)

28 Views Asked by At

I am trying to show an error message from an external library in QTextEdit.

Here is a simple example code:

mainwindow.h:

#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>

QT_BEGIN_NAMESPACE
class QPushButton;
class QTextEdit;
QT_END_NAMESPACE

class MainWindow : public QMainWindow {
    Q_OBJECT
public:
    MainWindow();
    static void myErrorHandler(const char *msg);

private slots:
    void handleButton();
private:
    QPushButton *errorButton;
    QTextEdit *textEdit;
};
#endif

mainwindow.cpp:

#include <external/elib.h>
#include <QtWidgets>
#include <QMainWindow>
#include <QDebug>

#include "mainwindow.h"

void MainWindow::myErrorHandler(const char *msg) {
    qDebug () << "myErrorHandler: " << msg;  // this works
    // textEdit->append(msg);  // error: Invalid use of member 'textEdit' in static member function
}

MainWindow::MainWindow() {
    QWidget *widget = new QWidget;

    QString message = tr("Try me...");
    textEdit = new QTextEdit();
    textEdit->setPlainText(message);

    errorButton = new QPushButton("emit error", this);
    connect(errorButton, &QPushButton::released, this, &MainWindow::handleButton);

    QVBoxLayout *layout = new QVBoxLayout;
    layout->addWidget(textEdit);
    layout->addWidget(errorButton);
    widget->setLayout(layout);

    elibSetErrorHandler(myErrorHandler);
    setCentralWidget(widget);
}

void MainWindow::handleButton() {
    textEdit->append(tr("<b>errorButton</b> pressed"));
    // Do something that cause error in external library
}


int main(int argc, char *argv[]) {
    QApplication app(argc, argv);
    MainWindow window;
    window.show();
    return app.exec();
}

There is void elibSetErrorHandler(void(*handler)(const char *)); in external/elib.h.

I also tried to emit the signal displayError(QString::fromStdString(msg)) from myErrorHandler, but it caused another error:

Call to non-static member function without an object argument

0

There are 0 best solutions below