qt 结构体变量转换为qbytearray
时间: 2024-03-23 13:41:41 浏览: 33
可以使用QDataStream来将结构体变量转换为QByteArray。下面是一个示例代码:
```c++
#include <QtCore>
struct MyStruct {
qint32 id;
QString name;
double value;
};
QDataStream &operator<<(QDataStream &out, const MyStruct &s)
{
out << s.id << s.name << s.value;
return out;
}
QDataStream &operator>>(QDataStream &in, MyStruct &s)
{
in >> s.id >> s.name >> s.value;
return in;
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
MyStruct s = { 1, "Test", 3.14 };
QByteArray byteArray;
QDataStream stream(&byteArray, QIODevice::WriteOnly);
stream << s;
qDebug() << byteArray.toHex();
return a.exec();
}
```
在上面的示例中,我们定义了一个名为MyStruct的结构体,并重载了QDataStream的<<和>>运算符。之后我们创建了一个MyStruct类型的变量s,并使用QDataStream将其写入到QByteArray中。最后我们将QByteArray以十六进制的形式输出到控制台。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)