如何将python的字节数组转换为QByteArray?

时间:2021-10-16 04:46:07

I have a python ‘s byte array b=b'hello' and I want to use it as the parameter of QtextStream to create a QtextStream object ,but QtextStream accept Qt’s byte array rather than Python’s .I wonder is there anyway to to convert python ‘s byte array to QByteArray ?

我有一个python的字节数组b=b'hello',我想用它作为QtextStream的参数来创建一个QtextStream对象,但是QtextStream接受Qt的字节数组,而不是python的字节数组。

I’ve tested the following code ,it seems I cannot do it in this way .

我已经测试了下面的代码,看起来我不能这样做。

>>> b=b'hello'
>>> from PyQt4.QtCore import *
>>> c=QTextStream(QByteArray(b)).readAll()
>>> c
''
>>>

1 个解决方案

#1


0  

I guess the issue is that QByteArray object is constructed, passed to the QTextStream and then immediately destroyed. QTextStream doesn't make a copy of data, it only keeps a pointer to the data source. Since the source is destroyed, no data can be longer read. I even managed to get segmentation fault error when trying to call readAll() using some variations of your code. So, the solution is to store your QByteArray object in a variable as long as you need it.

我想问题是QByteArray对象被构造,传递到QTextStream,然后立即被销毁。QTextStream不会复制数据,它只保留一个指向数据源的指针。由于源被销毁,所以没有数据可以被读取。我甚至在尝试调用readAll()时使用了一些代码的变体,从而获得了分段错误错误。因此,解决方案是在变量中存储QByteArray对象,只要您需要它。

>>> buf = QByteArray(b)
>>> c = QTextStream(buf).readAll()
>>> c
PyQt4.QtCore.QString(u'hello')

The original question 'how to convert python ‘s byte array to QByteArray?' do not refer to your issue. It easy to see that it can be done using the obvious way:

最初的问题是“如何将python的字节数组转换为QByteArray?”不要提及你的问题。很容易看出它可以用明显的方法来完成:

>>> QByteArray(b)
PyQt4.QtCore.QByteArray('hello')

#1


0  

I guess the issue is that QByteArray object is constructed, passed to the QTextStream and then immediately destroyed. QTextStream doesn't make a copy of data, it only keeps a pointer to the data source. Since the source is destroyed, no data can be longer read. I even managed to get segmentation fault error when trying to call readAll() using some variations of your code. So, the solution is to store your QByteArray object in a variable as long as you need it.

我想问题是QByteArray对象被构造,传递到QTextStream,然后立即被销毁。QTextStream不会复制数据,它只保留一个指向数据源的指针。由于源被销毁,所以没有数据可以被读取。我甚至在尝试调用readAll()时使用了一些代码的变体,从而获得了分段错误错误。因此,解决方案是在变量中存储QByteArray对象,只要您需要它。

>>> buf = QByteArray(b)
>>> c = QTextStream(buf).readAll()
>>> c
PyQt4.QtCore.QString(u'hello')

The original question 'how to convert python ‘s byte array to QByteArray?' do not refer to your issue. It easy to see that it can be done using the obvious way:

最初的问题是“如何将python的字节数组转换为QByteArray?”不要提及你的问题。很容易看出它可以用明显的方法来完成:

>>> QByteArray(b)
PyQt4.QtCore.QByteArray('hello')