QT 自定義結構體的內容儲存在dat檔案中

2021-10-06 02:44:43 字數 1489 閱讀 8534

使用的是qdatastream進行檔案資料流的儲存

qt自帶的qdatastream只能傳遞它自己要求的資料型別。但是我們可以自己過載qdatastream& operator<<()和qdatastream& operator>>();這樣我們就可以傳遞struct的型別了

1、首先新建乙個類,儲存三個不同型別的字段資訊;

class t

;t::t(int a1, double b1, qstring c1)

2、分別重寫檔案讀寫操作

qdatastream& operator <<(qdatastream &out, const t &t)

qdatastream& operator >>(qdatastream &in, t &t)

3、分別在main函式進行相對應的檔案操作即可

//檔案寫入

t t(1, 2, "3");

qfile writefile("test.dat");

writefile.open(qiodevice::writeonly);

qdatastream out(&writefile);

out << t;

writefile.close();

//檔案讀取

qfile readfile("test.dat");

readfile.open(qiodevice::readonly);

qdatastream in(&readfile);

in >> t;

readfile.close();

qdebug() << t.a << t.b << t.c;

注意最開始的引用:

字串寫入 序列化的示例

#include #include #include #include using namespace std;

qbytearray testserialout()

{ //資料

int nversion = 1;

double dblvalue = 125.78999;

qstring strname = qobject::tr("this an example.");

//位元組陣列儲存結果

qbytearray baresult;

//序列化的流

qdatastream dsout(&baresult, qiodevice::readwrite); //做輸出,建構函式用指標

//設定qt序列化版本

dsout.setversion(qdatastream::qt_5_0);//使用qt 5.0 版本流

//序列化輸出

dsout<>nversion>>dblvalue>>strname;

//列印

qdebug()<

Qt訊號槽傳遞自定義結構體

qt的訊號和槽可以傳遞int double等c 常用型別變數,也可以傳遞qvector qmap等qt的容器類 當然也可以傳遞qt定義的型別 那麼qt的訊號和槽如何傳遞自定義的結構體呢。首先在定義結構體的同時需要使用q declare metatype。通過這個巨集定義可以將自定義的型別註冊到qt的...

自定義結構體封裝

使用nsvalue如下方法進行裝箱 nsvalue valuewithbytes const void value objctype const char type 呼叫下面的方法進行拆箱 void getvalue void value main.m foundationframework cre...

自定義型別 結構體

struct tag 結構體型別名稱 variable list 結構體變數 省略結構體型別名稱 匿名結構體型別 當省略掉結構體型別名稱時,就不能省略掉結構體變數,這樣是不合理的,所以一般我們不建議省略結構體型別名 struct x,y 全域性變數 struct a 20 p int main 注意...