如何使用QTextStream读取行一次一个,使用定时器

How to use QTextStream readline one at the time, using timer

本文关键字:一个 定时器 QTextStream 何使用 读取 一次      更新时间:2023-10-16

我想使用计时器每秒读取一行文件。计时器启动后,读取第一行,一秒钟后,读取第二行。。。。。。

但在QTextStream中并没有读取特定行的功能。关于如何实现这一点,有什么想法吗?

如果我运行以下代码,它将始终返回

 QTextStream: no device
 QTextStream: no device
 QTextStream: no device
 QTextStream: no device
timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(sendmsg()));

void simulatorwindow::on_simON_clicked()
{ 
    simfile = QFileDialog::getOpenFileName(this, tr("Open"),"", tr("Files (*.txt)"));  
    QFile simfile(simfile);
    if (!simfile.open(QIODevice::ReadOnly | QIODevice::Text))
    return; 
    QTextStream textsim(&simfile); 
    timer->start(1000);
    qDebug("Start simulation");
}
void simulatorwindow::on_simOFF_clicked()
{ 
    timer->stop();
    qDebug("Stop simulation");
}
void simulatorwindow::sendmsg()
{ 
    QString line = textsim.readLine();
    QString title = line.section(',', 0,0);
    QString chopped = line.section(',', 1,1);
}

on_simON_clicked中,将textsim定义为局部变量,并在sendmsg中使用同名变量。但它不是同一个变量!

on_simON_clicked中,您应该使用(显然)成员变量,因为局部变量在函数之外不可用。如果你在编译器中打开更多的警告,你会得到一个关于局部变量"影子"为成员/全局变量的警告。

与其每次定时器插槽启动时都打开文件,不如将QFile作为simulatorwindow的成员。当程序启动时打开它,每当计时器启动时从中读取。