qdialog中qtextbrowser的动态更新来自文件(由另一个作业更新)

Dynamic update of QTextBrowser in a Qdialog from a file(that gets updated by another job)

本文关键字:更新 另一个 作业 文件 qtextbrowser 动态 qdialog      更新时间:2023-10-16

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

.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();
}

因此,我只能在第一个呼叫上读取文件,其余的呼叫以获取文件的更新不起作用。

预先感谢

您需要在初始读取后在输入流中调用std::ios::clear()。当您读取整个文件时,它将在流中设置failbit并拒绝继续读取,即使文件在此期间发生了变化。

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

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

完整的代码在以下链接中