Search code examples
pythonpyqttextedit

pyqt - How to change the color of a word from my textedit


This is a method to copy a word from my textedit, and set it to a new line into my tableview. What i need is: How to change the color of the word that i selected into my textedit? The name of my text edit is "editor", when i copy the word i need change the color of this word, and i dont know how to do it. help please :). With examples please ~~

 def addLineTable(self):

    row = self.model.rowCount()   #create a line into my tableview
    self.model.insertRows(row)
    column = 0
    index = self.model.index(row, column)        
    tableView = self.TABLE            
    tableView.setFocus()
    tableView.setCurrentIndex(index)
    cursor = self.editor.textCursor()
    textSelected = cursor.selectedText()  #set text to cursor
    self.model.setData(index, QVariant(textSelected)) #set text to new tableview line

Solution

  • If I understand your question correctly, you just want to change the color of the text, right? You can do that by assigning StyleSheets with css to your QWidgets, documentation here.

    A sample below:

    from PyQt4 import QtGui, QtCore
    
    class Window(QtGui.QDialog):
        def __init__(self):
            QtGui.QDialog.__init__(self)
            self._offset = 200
            self._closed = False
            self._maxwidth = self.maximumWidth()
            self.widget = QtGui.QWidget(self)
            self.listbox = QtGui.QListWidget(self.widget)
            self.editor = QtGui.QTextEdit(self)
            self.editor.setStyleSheet("QTextEdit {color:red}")
            layout = QtGui.QHBoxLayout(self)
            layout.addWidget(self.widget)
            layout.addWidget(self.editor)
    
    if __name__ == '__main__':
    
        import sys
        app = QtGui.QApplication(sys.argv)
        window = Window()
        window.move(500, 300)
        window.show()
        sys.exit(app.exec_())
    

    Edit

    Or you can setStyleSheet to all your QTextEdit, try this:

    ......
    
    app = QtGui.QApplication(sys.argv)
    app.setStyleSheet("QTextEdit {color:red}")
    ......