3

我有一个在作业运行时更新的日志文件。我希望在文本浏览器中显示文本内容,并且应该动态更新。

.h 文件

public:

    void fillloginfo();

    void initializeQTimer();

    void closeEvent(QCloseEvent *event);

    void fillLogInfoChronically(const QString& logFilePath);

private:

    QTimer* m_Timer;

    QString m_logFilePath;

    std::ifstream m_logFileStream;

public slots:

    void fillLogInfoChronicallySlot();

.cpp 文件

void logdialog::initializeQTimer(){

    m_Timer = NULL;

    //create the timer object
    m_Timer = new QTimer(this);

    QObject::connect(m_Timer,SIGNAL(timeout()), this,SLOT(fillLogInfoChronicallySlot()));

 }

void logdialog::closeEvent(QCloseEvent *event)
{
    m_Timer->stop();

    if ( m_logFileStream.is_open()){
         m_logFileStream.close();
    }
}



void logdialog::fillLogInfoChronically(const QString &logFilePath)
{
    uilog->textBrowser->clear();

    m_LastLinePos = 0;

    m_logFilePath = logFilePath;

    std::string m_logFilePathStr= m_logFilePath.toStdString();
    m_logFileStream.open(m_logFilePathStr.c_str());

    if (m_logFileStream.is_open()){

        fillloginfo();

        m_Timer->start(1000);
    }
}

void logdialog::fillloginfo()
{
    std::string line;
    while (getline(m_logFileStream,line)){
        uilog->textBrowser->append(QString::fromStdString(line));
    }  
}

void logdialog::fillLogInfoChronicallySlot()
{
    fillloginfo();
}

所以,我只能在第一次调用时读取文件,其余从文件中获取更新的调用都不起作用。

提前致谢

4

1 回答 1

1

您需要std::ios::clear()在初始读取后调用输入流。当您读取整个文件时,它会failbit在流中设置 并拒绝继续读取,即使同时文件已更改。

在您的情况下,您必须在再次阅读之前做:

void logdialog::fillloginfo()
{
    std::string line;
    m_logFileStream.clear();
    while (getline(m_logFileStream,line)){
        uilog->textBrowser->append(QString::fromStdString(line));
    }
}

完整代码在以下链接中

于 2017-09-06T10:49:26.477 回答