【问题标题】:Qt 4.8 Why my QIODevice not output a text in this code?Qt 4.8 为什么我的 QIODevice 没有在这段代码中输出文本?
【发布时间】:2015-09-18 12:49:23
【问题描述】:

如果使用 QTextStream 控制台(stdout) - 一切正常,但如果我编写自定义 IODevice,在 qInstallMsgHandler() 之后控制台中没有文本

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;
}

我在文件 remoteconsole.h .cpp 中的 IODevice 实现

#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;
}

以后我想用 QTCPServer 扩展这个代码,它将调试输出发送到通过 telnet 或 nc 连接到设备的客户端。

【问题讨论】:

    标签: qt qiodevice


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-23
      • 2016-04-20
      • 2021-06-21
      • 1970-01-01
      • 1970-01-01
      • 2019-11-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多