0

I have a string in PYQT5 that I'm loading into a QLabel() that contains less than and greater than symbols. The output is omitting the symbols and everything in between them. Is there a way to output this string as-is?

Output


from PyQt5.QtWidgets import *
import sys

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setGeometry(100, 100, 400, 400)

        self.centralWidget = QWidget()
        self.setCentralWidget(self.centralWidget)
        
        self.label = QLabel()
        
        self.vLayout = QVBoxLayout()
        self.vLayout.addWidget(self.label)
        self.centralWidget.setLayout(self.vLayout)

        myString = 'Supply Issue < 20 VDC when Speed > 100 MPH'
        num = '10'

        self.label.setText(f'<font color = "#E4551F">{num}:</font> {myString}')


app = QApplication(sys.argv)
myWin = MainWindow()
myWin.show()
app.exec()

'''

  • What widget are you setting the text on? I don't think a QListWidget has text itself. If the HTML is the issue, you you should be able to use html.escape on the interpolated string to interpret it as normal characters instead of markdown – Numerlor Jan 20 '22 at 14:10
  • Are you using a custom delegate to show formatted text? Also, please provide a [mre]. – musicamante Jan 20 '22 at 14:14
  • Sorry - I was getting confused about where the problem was. It's in QLabel - I've fixed the question so that it should be much easier to answer. Thanks all – sethdhanson Jan 20 '22 at 14:55

1 Answers1

1

QLabels take HTML, so you can use html.escape on the value you are interpolating:

self.label.setText(f'<font color = "#E4551F">{num}:</font> {html.escape(myString)}')

This will convert < and > to &lt; and &gt;. It will also make & work correctly.

LeopardShark
  • 3,820
  • 2
  • 19
  • 33
  • Thank you! The other question on this topic was unclear and didn't answer it for me but you've shown me how to properly execute html.escape - very much appreciated! – sethdhanson Jan 21 '22 at 14:11