pythonpyqt5qbytearray

Is there a pyqt5 method to convert a python string to a QByteArray?


this is probably a very simple question but I haven't been able to find a good answer to it yet. I've found answers for converting QByteArrays into python strings, but not vice versa.

Is there a pyqt5 method that allows me to simply convert a python string into a QByteArray (so that it can be sent over a serial connection using QSerialPort.write()). I reckon it's likely that there is a nice built-in feature in pyqt5 to do this without manually extracting the bytes from the string and building a QByteArray from them?


Solution

  • You have to convert the string to bytes:

    >>> from PyQt5.QtCore import QByteArray
    >>> s = "hello world"
    >>> ba = QByteArray(s.encode())
    >>> print(ba)
    b'hello world'