我需要帮助更改 QTableView 中一个单词的颜色。
我需要做的是:当我在表中打开 csv 文件时,现在我的列~行中有句子/单词,我需要为一些单词着色,例如:
在这里你可以看到我的 csv 程序。 http://i.imgur.com/uIBQ2ch.jpg
示例:在 [3][0](4 行,1 列)中,我有“filme”这个词,正如您在我的图像中看到的那样。
我想给这个词上色,如果存在相同的词,在 [3][2](4 行,3 列)中我也想给这个词上色。
这是我的完整代码:
#!/usr/bin/env python
#-*- coding:utf-8 -*-
import sip
sip.setapi('QVariant', 2)
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import csv
try:
_fromUtf8 = QString.fromUtf8
except AttributeError:
_fromUtf8 = lambda s:s
class MyWindow(QWidget):
def __init__(self, fileName, parent=None):
super(MyWindow, self).__init__(parent)
self.fileName = fileName
self.model = QStandardItemModel(self)
self.tableView = QTableView(self)
self.tableView.setModel(self.model)
self.tableView.horizontalHeader().setStretchLastSection(True)
self.pushButtonLoad = QPushButton(self)
self.pushButtonLoad.setText("Load Csv File!")
self.pushButtonLoad.clicked.connect(self.on_pushButtonLoad_clicked)
self.pushButtonWrite = QPushButton(self)
self.pushButtonWrite.setText("Write Csv File!")
self.pushButtonWrite.setStyleSheet('color:red;background-color:rgb(155, 255, 153);border:1px solid purple;')
self.pushButtonWrite.clicked.connect(self.on_pushButtonWrite_clicked)
self.layoutVertical = QVBoxLayout(self)
self.layoutVertical.addWidget(self.tableView)
self.layoutVertical.addWidget(self.pushButtonLoad)
self.layoutVertical.addWidget(self.pushButtonWrite)
def loadCsv(self, fileName):
with open(fileName, "rb") as fileInput:
for row in csv.reader(fileInput):
items = [
QStandardItem(field.decode('utf8'))
for field in row
]
self.model.appendRow(items)
self.tableView.resizeRowsToContents()
self.model.setHeaderData(0, Qt.Horizontal, "Feature")
self.model.setHeaderData(1, Qt.Horizontal, "Polarity(-1,0,1)")
self.model.setHeaderData(2, Qt.Horizontal, "texto")
self.tableView.setColumnWidth(2,1000)
self.tableView.resizeRowsToContents()
def writeCsv(self, fileName):
with open(fileName, "w") as fileOutput:
writer = csv.writer(fileOutput)
for rowNumber in range(self.model.rowCount()):
fields = [
self.model.data(
self.model.index(rowNumber, columnNumber),
Qt.DisplayRole
)
for columnNumber in range(self.model.columnCount())
]
writer.writerow(fields)
@pyqtSlot()
def on_pushButtonWrite_clicked(self):
self.writeCsv(self.fileName)
@pyqtSlot()
def on_pushButtonLoad_clicked(self):
self.loadCsv(self.fileName)
if __name__ == "__main__":
import sys
app = QApplication(sys.argv)
app.setApplicationName('MyWindow')
main = MyWindow("marcoteste.csv")
main.show()
sys.exit(app.exec_())