0

If used QTextStream console(stdout) - all work just fine, but if I wrote custom IODevice, after qInstallMsgHandler() no text in console

main.cpp #include "remoteconsole.h"

#include <QCoreApplication>
#include <QDateTime>
#include <QTimer>

QTextStream *out;

void logOutput(QtMsgType type, const char *msg)
{
    QString debugdate = QDateTime::currentDateTime().toString("yyyy.MM.dd hh:mm:ss.zzz");
    *out << debugdate << " " << type << msg << endl;
}

int main(int argc, char *argv[])
{
    int i;
    QCoreApplication a(argc, argv);
    RemoteConsole * remote = new RemoteConsole(&a);
    QTextStream console((QIODevice *)remote);
    out = &console;
    qDebug() << "start qInstallMsgHandler";
    qInstallMsgHandler(logOutput);
    qDebug() << "end qInstallMsgHandler"<<endl;

    for(i=0;i<10;i++){
        qDebug() << i<<endl;
    }

    QTimer *timer = new QTimer();
    a.connect(timer, SIGNAL(timeout()), &a, SLOT(quit()));
    timer->start(5000);

    a.exec();
    return 0;
}

my IODevice implementation in file remoteconsole.h .cpp

#ifndef REMOTECONSOLE_H
#define REMOTECONSOLE_H

#include <QIODevice>
#include <QDebug>

class RemoteConsole: public QIODevice
{
    Q_OBJECT
public:
    RemoteConsole(QObject *parent);
    ~RemoteConsole();
private:
    Q_DISABLE_COPY(RemoteConsole)
protected:
     qint64 readData(char* data, qint64 maxSize);
     qint64 writeData(const char* data, qint64 maxSize);
};



#endif // REMOTECONSOLE_H

#include "remoteconsole.h"

RemoteConsole::RemoteConsole(QObject* parent=0) :
    QIODevice(parent)
{

}

RemoteConsole::~RemoteConsole(){}

qint64 RemoteConsole::readData(char *data, qint64 maxlen){
    qDebug() << data <<endl;
    return maxlen;
}

qint64 RemoteConsole::writeData(const char *data, qint64 len){
    printf("writeData");
    qDebug() << data <<endl;
    return len;
}

In future I want to expand this code with QTCPServer, that send debug outputs to client connected to the device by telnet or nc.

4

1 回答 1

1

调用后您不会在控制台中收到任何文本,qInstallMsgHandler因为您将所有调试数据发送到您的RemoteConsole对象中。

此外,您的代码中还有其他一些问题。

  1. 您应该先致电QIODevice::open,然后才能在该设备上进行操作。
  2. RemoteConsole::writeData函数中,您将有一个无限循环,因为您qDebug()在那里使用。qDebug()将调用logOutput哪个将RemoteConsole::writeData再次调用。
于 2015-09-18T15:14:30.160 回答