如何读写Qt集合类



我尝试实现函数,使用QDataStream写入和读取文件的QLinkedList<DataClass>。Qt文档(读写Qt集合类(在这一点上有点谨慎。

我的写入函数如下所示:

void
MainWindow::handle_btn_save_clicked()
{
auto fileName = QFileDialog::getSaveFileName(
this,
tr("Save Data"),
".",
tr("Files (*)") );
QFile file(fileName);
file.open(QIODevice::WriteOnly);
QDataStream dstream(&file);
// write table data to file
dstream << dataList; // QLinkedList<DataClass> *dataList;
file.close();
}

读取函数应如下所示

void
MainWindow::handle_btn_load_clicked()
{
auto fileName = QFileDialog::getOpenFileName(
this,
tr("Load Data"),
".",
tr("Files (*)") );
QFile file(fileName);
file.open(QIODevice::ReadOnly);
QDataStream dstream(&file);
QLinkedList<DataClass> *dl;
dstream >> dl;
file.close();
}

编译器抛出这个

/opt/Qt/5.10.1/gcc_64/include/QtCore/qdatastream.h:263: error: no match for ‘operator>>’ (operand types are ‘QDataStream’ and ‘QLinkedList<MainWindow::DataClass>::value_type {aka MainWindow::DataClass}’)
s >> t;
~~^~~~

如何以正确的方式做到这一点?


定义如下:

class DataClass
{
public:
int val0;
int val1;
int val2;
};

QDataStream知道如何序列化QLinkedList但不知道如何序列化DataClass因此您必须实现它:

class DataClass
{
public:
int val0;
int val1;
int val2;
friend QDataStream & operator<< (QDataStream& stream, const DataClass& s){
stream << s.val0 << s.val1 << s.val2;
return stream;
}
friend QDataStream & operator>> (QDataStream& stream, DataClass& s){
stream >> s.val0 >> s.val1 >> s.val2;
return stream;
}
};

例:

#include <QCoreApplication>
#include <QDataStream>
#include <QFile>
#include <QLinkedList>
class DataClass
{
public:
int val0;
int val1;
int val2;
friend QDataStream & operator<< (QDataStream& stream, const DataClass& s){
stream << s.val0 << s.val1 << s.val2;
return stream;
}
friend QDataStream & operator>> (QDataStream& stream, DataClass& s){
stream >> s.val0 >> s.val1 >> s.val2;
return stream;
}
};
static void save(QLinkedList<DataClass> l, const QString & fileName){
QFile file(fileName);
if(!file.open(QFile::WriteOnly))
return;
QDataStream dstream(&file);
dstream << l;
}
static QLinkedList<DataClass> read(const QString & fileName){
QLinkedList<DataClass> l;
QFile file(fileName);
if(file.open(QFile::ReadOnly)){
QDataStream dstream(&file);
dstream >> l;
}
return l;
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
const QString fileName = "test.txt";
QLinkedList<DataClass> in;
DataClass din;
din.val0 = 1;
din.val0 = 2;
din.val0 = 3;
in << din;
save(in, fileName);
QLinkedList<DataClass > out;
out = read(fileName);
DataClass dout = out.first();
Q_ASSERT(dout.val0 == din.val0);
Q_ASSERT(dout.val1 == din.val1);
Q_ASSERT(dout.val2 == din.val2);
return 0;
}

相关内容

  • 没有找到相关文章

最新更新