您可以使用计时器来触发连续行的读取。此功能是最好的分离成其自己的类,每次一个新行可发出信号:
// https://github.com/KubaO/stackoverflown/tree/master/questions/timed-read-44319722
#include <QtWidgets>
class PeriodicReader : public QObject {
Q_OBJECT
QTimer m_timer{this};
QFile m_file{this};
void readLine() {
if (m_file.atEnd()) {
m_timer.stop();
return;
}
emit newLine(m_file.readLine());
}
public:
explicit PeriodicReader(QObject * parent = {}) : QObject(parent) {
connect(&m_timer, &QTimer::timeout, this, &PeriodicReader::readLine);
}
void load(const QString & fileName) {
m_file.close(); // allow re-opening of the file
m_file.setFileName(fileName);
if (m_file.open(QFile::ReadOnly | QFile::Text)) {
readLine();
m_timer.start(300); // 0.3s interval
}
}
Q_SIGNAL void newLine(const QByteArray &);
};
因为我们使用了一个QPlainTextEdit
显示的文本,我们需要的原料线转换成字符串。
QString lineToString(QByteArray line) {
while (line.endsWith('\n') || line.endsWith('\r'))
line.chop(1);
return QString::fromUtf8(line);
}
它现在是一个简单的事情,把它连成一个演示:
int main(int argc, char ** argv) {
QApplication app{argc, argv};
QWidget window;
QVBoxLayout layout{&window};
QPushButton load{"Load"};
QPlainTextEdit edit;
layout.addWidget(&load);
layout.addWidget(&edit);
window.show();
PeriodicReader reader;
QObject::connect(&load, &QPushButton::clicked, [&]{
auto name = QFileDialog::getOpenFileName(&window);
if (!name.isEmpty()) {
edit.clear(); // allow re-opening of the file
reader.load(name);
}
});
QObject::connect(&reader, &PeriodicReader::newLine, &edit,
[&](const QByteArray & line){ edit.appendPlainText(lineToString(line)); });
return app.exec();
}
#include "main.moc"
这结束了完整的例子,因为QPlainTextEdit::appendPlainText
已经增加了一个段落的结束,我们必须删除任何行结尾。
向我们展示使用'readLine'读取文件的代码。我想你在调用'readLine'之后关闭了流,因此每次执行代码时,它总是从第一行开始。相反,你不应该在达到'EOF'之前关闭流。 – putu
void ReadTextFile :: on_pushButton_4_clicked() QFile textfile(“my_file_here”); (textfile.open(QIODevice :: ReadOnly)|| QIODevice :: Text) { QTextStream in(&textfile); (!in.atEnd()) QString line = in.readLine(); ui-> textEdit-> append(line); } textfile.close(); qDebug()<<“关闭文本文件”; } qDebug()<<“Out Pushbutton File”; } –
对不起,我不知道如何使用插入编码像你的 –