QByteArray 和 QString 转换的问题

problems with QByteArray and QString convertion

本文关键字:问题 转换 QString QByteArray      更新时间:2023-10-16

我有一个服务器和一个客户端,它们通过TCP(QTcpSocket和QTcpServer(连接。 数据使用 QByteArray 发送。

void Receive::newConnection()
{
while (server->hasPendingConnections())
{
QTcpSocket *socket = server->nextPendingConnection();
connect(socket, SIGNAL(readyRead()), SLOT(readyRead()));
connect(socket, SIGNAL(disconnected()), SLOT(disconnected()));
QByteArray *buffer = new QByteArray();
qint32 *s = new qint32(0);
buffers.insert(socket, buffer);
sizes.insert(socket, s);
qDebug()<<buffer;
}
}

最后一行在服务器控制台中打印在客户端中输入的文本。 我想将缓冲区转换为 QString。(或者我想把它发送到QML文件(。所以当我尝试时:

QString receivedText = QTextCodec::codecForMib(1015)->toUnicode(buffer);

并给我错误:

no matching function for call to 'QTextCodec::toUnicode(QByteArray*&)'
receivedText = QTextCodec::codecForMib(1015)->toUnicode(buffer);
^

当使用fromAscii或fromStringC时,它说它不是QString的成员。

我该怎么办?

根据文档:

QString QTextCodec::toUnicode(const QByteArray &a( const

将此编解码器的编码转换为 Unicode,并返回 导致 QString。

综上所述,需要引用而不是指针。在您的情况下,您应该将其更改为:

QString receivedText = QTextCodec::codecForMib(1015)->toUnicode(*buffer);