Qt GUI-只想在值更改时读取.txt文件

Qt GUI - Want to read from .txt file only when the value is changed

本文关键字:读取 txt 文件 GUI- 只想 Qt      更新时间:2023-10-16

我实现了一个QTimer对象,用信号通知一个函数每秒从.txt文件读取一次,并创建另一个类的新对象。我的问题是,我想限制我的函数只创建一个对象,并不断检查.txt文件是否有任何更改。如何做到这一点?

以下是每秒钟执行一次的代码

void PutMeDown::signalReceived()
{
    char buffer;
    char currentState;
    char prevState = '0';
    int fd = open("/home/stud/test", O_RDWR, 0666);
    if(fd < 0)
        cout << "can't open file" << endl;
    else
        read(fd, &buffer, 1);//read from file
    currentState = buffer;
    if(currentState == prevState)
    {
        drive = new Drive(this);
        drive->setWindowFlags(Qt::Window | Qt::FramelessWindowHint);
        drive->show();
        this->hide();
    }
    close(fd);
}

Qt-QFileSystemWatcher中有一个特殊的类。这个类可以告诉您文件已更改(fileChanged信号)。

QFileSystemWatcher * watcher = new QFileSystemWatcher(this);
watcher->addPath(mFileName);
connect(watcher,SIGNAL(fileChanged(QString)),SLOT(slot(QString)));

在插槽中,您可以读取文件或做其他事情。有了这个类,您就不需要使用QTimer,它比每秒检查一次文件要好。

回到你关于1个物体的问题。最简单的解决方案是提供额外的bool变量,在slot中检查该变量并创建新对象。您还可以提供一些方法将此变量更改为"外部",以便在需要时创建对象。

我还看到您使用non-Qt方法来读取文件。Qt中也有一个特殊的类:QFile。检查一下,也许你的任务允许你使用QFile