1

我已经实现了一个 QTimer 对象来指示一个函数,该函数每秒从 .txt 文件中读取并创建另一个类的新对象。我的问题是我想将我的函数限制为仅创建 1 个对象并继续检查 .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);
}
4

1 回答 1

3

Qt-中有特殊课程QFileSystemWatcher。此类可以告诉您文件已更改(fileChanged信号)。

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

在插槽中,您可以读取文件或执行其他操作。有了这个你不需要使用的类QTimer,它可以比每秒检查文件更好。

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

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

于 2014-11-06T19:20:56.033 回答