Question

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
Was it helpful?

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}")
......

OTHER TIPS

You're already getting the QTextCursor. All you need to do is apply a format (QTextCharFormat) to this cursor and the selected text will be formatted accordingly:

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()

    # get the current format
    format = cursor.charFormat()
    # modify it
    format.setBackground(QtCore.Qt.red)
    format.setForeground(QtCore.Qt.blue)
    # apply it
    cursor.setCharFormat(format)

    textSelected = cursor.selectedText()  #set text to cursor
    self.model.setData(index, QVariant(textSelected)) #set text to new tableview line
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top