[英]Qt - QTextStream - How to set cursor position to beginning of a line?
After readLine()
, how to set cursor position to the beggining of a line? 在readLine()
,如何将光标位置设置为行的开头?
Using seek()
and pos()
doesnt work for me. 使用seek()
和pos()
对我不起作用。
Here is how my file.txt look like: 这是我的file.txt的样子:
Object1 Some-name 2 3.40 1.50
Object2 Some-name 2 3.40 1.50 3.25
Object3 Some-name 2 3.40 1.50
Here's my code: 这是我的代码:
QFile file("file.txt");
if(file.open(QIODevice::ReadOnly | QIODevice::Text)) {
QTextStream stream(&file);
while(!stream.atEnd()) {
qint64 posBefore = file.pos();
QString line = stream.readLine();
QStringList splitline = line.split(" ");
if(splitline.at(0) == "Object1") {
stream.seek(posBefore);
object1 tmp;
stream >> tmp;
tab.push_back(tmp);
}
if(splitline.at(0) == "Object2") {
stream.seek(posBefore);
object2 tmp;
stream >> tmp;
tab.push_back(tmp);
}
if(splitline.at(0) == "Object3") {
stream.seek(posBefore);
object3 tmp;
stream >> tmp;
tab.push_back(tmp);
}
}
file.close();
}
So, you need (de)serialization . 因此,您需要(反序列化) 。
Try to do it right. 尝试做正确的事。 Here is official documentation: http://qt-project.org/doc/qt-4.8/datastreamformat.html Here is example: Serialization with Qt 这是官方文档: http : //qt-project.org/doc/qt-4.8/datastreamformat.html这是示例: 使用Qt进行序列化
I've made a simple console app for you. 我为您制作了一个简单的控制台应用程序。 All you need to do is a good old QString::split()
by spaces and take the first element in the row however you like, i did it via QString::section()
method. 您需要做的是使用空格QString::split()
旧的QString::split()
并获取行中的第一个元素,但是您愿意,我是通过QString::section()
方法实现的。
Well here is the code for main.cpp : 好了,这是main.cpp的代码:
#include <QtCore/QCoreApplication>
#include <QFile>
#include <QStringList>
#include <QDebug>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QFile f("file.txt");
f.open(QIODevice::ReadOnly);
// next line reads all file, splits it by newline character and iterates through it
foreach (QString i,QString(f.readAll()).split(QRegExp("[\r\n]"),QString::SkipEmptyParts)){
QString name=i.section(" ",0,0);
// we take first section of string from the file, all strings are stored in "i" variable
qDebug()<<"read new object - "<<name;
}
f.close();
return a.exec();
}
File file.txt is in the same directory as the executable file and is copy of your file: 文件file.txt与可执行文件位于同一目录中,并且是文件的副本:
Object1 Some-name 2 3.40 1.50
Object2 Some-name 2 3.40 1.50 3.25
Object3 Some-name 2 3.40 1.50
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.