您可以使用計時器來觸發連續行的讀取。此功能是最好的分離成其自己的類,每次一個新行可發出信號:
// 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」; } –
對不起,我不知道如何使用插入編碼像你的 –