i need help changing the color of one word in my QTableView.
What i need to do is: when i open the csv file in my table, now i have sentences/words in my columns~rows and i need to color some words, like:
Here you can see my program with my csv. https://i.stack.imgur.com/NwO1C.jpg
Example: In the [3][0] ( 4 row, 1 column) i have the word "filme" as u can see in my image.
I want to color this word, and if exists the same word, in the [3][2] ( 4 row, 3 column) i want to color this word too.
Here is my full code:
#!/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_())