Changing a single strings color within a QTextEdit

后端 未结 3 1550
春和景丽
春和景丽 2021-02-06 03:10

I am working on a GUI developed via PyQt and Qt4. Within my GUI I have a QTextEdit that has various data written to. Is there a way in which I can manipulate the color of one wo

3条回答
  •  甜味超标
    2021-02-06 03:56

    After some research into other methods people have used, I figured it out and wanted to share. I tried the ".setHtml" function with the QTextEdit, but it didn't work.

    I figured out you can change the text color, add your text and then change it again and any text that's added after you've changed the color turns to that color, but nothing else.

    Here's an example.

    redColor = QColor(255, 0, 0)
    blackColor = QColor(0, 0, 0)
    
    self.myTextEdit.setTextColor(redColor)
    
    redText = "I want this text red"
    self.myTextEdit.write(redText)
    
    
    self.myTextEdit.setTextColor(blackColor)
    
    blackText = "And this text black"
    self.myTextEdit.append(blackText)
    

    And also, I want to add. ".write" and ".append" functions don't work for my "QTextEdit" class. Not sure if yours do, but what worked for me was the ".insertPlainText" function. Just convert your string to a "QString" like so

    blackText = QString(blackText)
    

提交回复
热议问题