Skip to content

Commit d2fa3f8

Browse files
committed
Fixed logs from another thread
1 parent 4f349ba commit d2fa3f8

File tree

2 files changed

+21
-6
lines changed

2 files changed

+21
-6
lines changed

qt/logger.cpp

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
#include "logger.h"
77
#include <QDebug>
88
#include <QScrollBar>
9+
#include <QObject>
910

1011
Logger *Logger::logger;
1112
QTextEdit *Logger::logTextEdit;
@@ -53,12 +54,12 @@ void Logger::logHandler(QtMsgType type, const QMessageLogContext &context ,
5354

5455
logTextEdit->verticalScrollBar()->
5556
setValue(logTextEdit->verticalScrollBar()->maximum());
56-
5757
}
5858
}
5959

6060
Logger::Logger()
6161
{
62+
QObject::connect(this, SIGNAL(log(QString)), this, SLOT(slotLog(QString)));
6263
qInstallMessageHandler(logHandler);
6364
oldBuf = std::cerr.rdbuf();
6465
std::cerr.rdbuf(this);
@@ -102,16 +103,21 @@ void Logger::setTextEdit(QTextEdit *textEdit)
102103

103104
std::basic_streambuf<char>::int_type Logger::overflow(int_type v)
104105
{
105-
qCritical() << tempBuf;
106+
emit log(tempBuf);
106107
tempBuf.clear();
107108

108109
return v;
109110
}
110111

111112
std::streamsize Logger::xsputn(const char *p, std::streamsize n)
112113
{
113-
tempBuf.append(p);
114+
tempBuf.append(QString::fromLatin1(p, n));
114115

115116
return n;
116117
}
117118

119+
void Logger::slotLog(QString msg)
120+
{
121+
qCritical() << msg;
122+
}
123+

qt/logger.h

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,13 +10,16 @@
1010
#include <iostream>
1111
#include <streambuf>
1212

13-
class Logger: public std::basic_streambuf<char>
13+
class Logger: public QObject, public std::basic_streambuf<char>
1414
{
15+
Q_OBJECT
16+
17+
private:
1518
static QTextEdit *logTextEdit;
1619
static Logger *logger;
1720
static int refCount;
18-
std::streambuf *oldBuf;
19-
QString tempBuf;
21+
std::streambuf *oldBuf = nullptr;
22+
QString tempBuf = "";
2023

2124
explicit Logger();
2225
~Logger();
@@ -28,10 +31,16 @@ class Logger: public std::basic_streambuf<char>
2831
virtual std::basic_streambuf<char>::int_type overflow(int_type v) override;
2932
virtual std::streamsize xsputn(const char *p, std::streamsize n) override;
3033

34+
private slots:
35+
void slotLog(QString msg);
36+
3137
public:
3238
static Logger *getInstance();
3339
static void putInstance();
3440
static void setTextEdit(QTextEdit *textEdit);
41+
42+
signals:
43+
void log(QString msg);
3544
};
3645

3746
#endif // LOGGER_H

0 commit comments

Comments
 (0)