pyqt-如何从我的textedi更改单词的颜色

2024-03-28 20:19:44 发布

您现在位置:Python中文网/ 问答频道 /正文

这是一种从我的textedit中复制一个单词并将其设置为新的行到我的tableview中的方法。我需要的是:如何改变我选择的文字的颜色到我的文字编辑?我的文本编辑的名字是“编辑器”,当我复制这个词时,我需要改变这个词的颜色,我不知道怎么做。请帮忙:)。请举例说明~ ~

 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

Tags: totextselfindexmodel颜色linecolumn
2条回答

你已经得到了QTextCursor。您只需将格式(^{})应用于此光标,所选文本将相应地格式化:

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

如果我正确地理解了你的问题,你只想改变文本的颜色,对吧? 你可以用css把StyleSheets分配给你的QWidgets,文档here

样本如下:

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

编辑

或者可以将样式表设置为所有的QTextEdit,请尝试以下操作:

......

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

相关问题 更多 >