-1

In Python3, if I need to put non-printable characters in a string or byte string, I can use

mystring     =  '\x00\x01'
mybytestring = b'\x00\x01'

where \x00 corresponds to ASCII 0 and \x01 is ASCII 1

>>> mystring = '\x00\x01'
>>> print(mystring)
 ☺
>>> ord(mystring[0])
0
>>> ord(mystring[1])
1
>>> mybytestring = b'\x00\x01'
>>> mybytestring[0]
0
>>> mybytestring[1]
1

If I try to do this by grabbing the text from a QLineEdit, the forward slashes seem to get escaped and I cannot figure out a good way to "unescape" them. Minimal PyQt example:

from PyQt5.QtWidgets import (QWidget, QApplication, QLineEdit)
import sys

class Example(QWidget):    
    def __init__(self):
        super().__init__()

        self.myedit = QLineEdit(self)
        self.myedit.move(10,10)
        self.myedit.returnPressed.connect(self.on_myedit_returnPressed)
        self.setGeometry(500, 500, 200, 50)
        self.show()

    def on_myedit_returnPressed(self):
        text = self.myedit.text()
        print('text: ', text)
        for i in range(len(text)):
            print(text[i])

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

enter image description here

And console output is:

text: \x00\x01 \ x 0 0 \ x 0 1 So it's behaving as if I typed in a string '\\x00\\x01' and escaped the forward slashes.

I'm trying to make a serial monitor application where I can send bytes to an Arduino over a serial port. But I'm stuck at being able to enter those bytes into a Qt input widget.

bfris
  • 4,147
  • 1
  • 19
  • 31

1 Answers1

1

you can use it like this:

text = self.myedit.text().encode().decode('unicode-escape')

Hope that works for you

Abdeslem SMAHI
  • 378
  • 1
  • 12