qtqiodevice

Qt 4.8 Why my QIODevice not output a text in this code?


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.


Solution

  • You don't get any text in console after qInstallMsgHandler call because you send all debug data into your RemoteConsole object.

    Also you've got some other problems in your code.

    1. You should call QIODevice::open before you can operate on that device.
    2. In the RemoteConsole::writeData function you will have an infinite loop because you use qDebug() there. qDebug() will call logOutput which will call RemoteConsole::writeData again.