PyQt5 Preserve Hex Characters from QLineEdit or other Qt Widgets

Question:

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

mystring     =  'x00x01'
mybytestring = b'x00x01'

where x00 corresponds to ASCII 0 and x01 is ASCII 1

>>> mystring = 'x00x01'
>>> print(mystring)
 ☺
>>> ord(mystring[0])
0
>>> ord(mystring[1])
1
>>> mybytestring = b'x00x01'
>>> 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: x00x01

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.

Asked By: bfris

||

Answers:

you can use it like this:

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

Hope that works for you

Answered By: Abdeslem SMAHI
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.