pyqt - 如何更改文本编辑器中单词的颜色
这是一个方法,用来从我的文本编辑器中复制一个单词,并把它放到我的表格视图的新行里。我需要的是:如何改变我在文本编辑器中选中的单词的颜色?我的文本编辑器叫“editor”,当我复制这个单词时,我想改变这个单词的颜色,但我不知道该怎么做。请帮帮我 :)。最好能给我一些例子~~
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
2 个回答
3
你已经得到了一个 QTextCursor
。你需要做的就是给这个光标应用一个格式(QTextCharFormat
),这样选中的文字就会按照这个格式进行显示:
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
3
如果我理解你的问题没错的话,你只是想改变文字的颜色,对吧?
你可以通过给你的 QWidgets
赋予 StyleSheets
来实现这一点,相关的文档可以在 这里 找到。
下面是一个示例:
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
使用 setStyleSheet,试试这个:
......
app = QtGui.QApplication(sys.argv)
app.setStyleSheet("QTextEdit {color:red}")
......