PyQt6 - Color different keywords in QTableWidget cell text
-
I need to change the color of a keyword if found inside the cell of a QTableWidget for PyQt6
In my example: if '1' appears in a cell,
change the color to REDSo it looks like this:
import sys from PyQt6.QtWidgets import QApplication, QTableWidget, QTableWidgetItem data = {'col1': ['one','highlight only 1','test'], 'col2': ['cool','4','um'], 'col3': ['123','1','2']} class TableView(QTableWidget): def __init__(self, data, *args): QTableWidget.__init__(self, *args) self.data = data self.setData() self.resizeColumnsToContents() self.resizeRowsToContents() def setData(self): horHeaders = [] for n, key in enumerate(sorted(self.data.keys())): horHeaders.append(key) for m, item in enumerate(self.data[key]): newitem = QTableWidgetItem(item) self.setItem(m, n, newitem) self.setHorizontalHeaderLabels(horHeaders) def main(args): app = QApplication(args) table = TableView(data, 3, 3) table.show() sys.exit(app.exec()) if __name__ == "__main__": main(sys.argv)
-
@zeroalpha
You show that you want to color substring1
wherever it appears it any cell. SinceQTableWidgetItem
s do not accept rich/HTML text you will need one of:-
Use
setCellWidget()
to make every cell hold e.g. aQLabel
orQTextEdit
into which you put rich text with necessary coloring. Not recommended because you will have many cell widgets which is inefficient, plus you will iterate every item and alter its content to do the coloring/uncoloring. -
Write a custom
QStyledItemDelegate
which outputs the HTML for the cell when called. Preferable.
-
-
@zeroalpha
I would Google forqstyleditemdelegate html
orqstyleditemdelegate rich text
. What about Displaying QTableWidgetItem's text with different colors via a QStyledItemDelegate or How to make item view render rich (html) text in Qt ?