PyQT:覆盖TableView中突出显示的文本颜色

时间:2013-04-11 18:42:17

标签: pyqt

我有一个表格视图,其中每个单元格都有自定义文本颜色。选择行后,颜色将更改为默认的highlightText值(白色)。当选择行时,如何保持定义的ForegroundRole指定颜色?谢谢你的帮助。

1 个答案:

答案 0 :(得分:1)

您可以使用自定义委托来实现此目的。

使用here中的提示尝试此操作。

from PyQt4 import QtGui, QtCore
import sys


class CustomSelectColorDelegate(QtGui.QStyledItemDelegate):

    def __init__(self, parent = None):
        super(CustomSelectColorDelegate, self).__init__(parent)

    def paint(self, painter, option, index):
        painter.save()

        # set background color
        if option.state & QtGui.QStyle.State_Selected:
            painter.setBrush(QtGui.QBrush(QtCore.Qt.white))
        else:
            painter.setBrush(QtGui.QBrush(QtCore.Qt.red))
        painter.drawRect(option.rect)

        # set text color
        if option.state & QtGui.QStyle.State_Selected:
            painter.setPen(QtGui.QPen(QtCore.Qt.red))
        else:
            painter.setPen(QtGui.QPen(QtCore.Qt.white))

        value = index.data(QtCore.Qt.DisplayRole)
        if value.isValid():
            text = value.toString()
            painter.drawText(option.rect, QtCore.Qt.AlignLeft | QtCore.Qt.AlignCenter, text)

        painter.restore()


if __name__ == '__main__':

    app = QtGui.QApplication(sys.argv)
    mw = QtGui.QWidget()

    tableViewer0 = QtGui.QTableWidget()

    newitem1 = QtGui.QTableWidgetItem('this is standard text')
    newitem2 = QtGui.QTableWidgetItem('this is custom text')

    tableViewer0.setColumnCount(2)
    tableViewer0.insertRow(0)
    tableViewer0.setItem(0, 0, newitem1)
    tableViewer0.setItem(0, 1, newitem2)

    customSelectColorDelegate = CustomSelectColorDelegate()
    tableViewer0.setItemDelegateForColumn(1, customSelectColorDelegate)


    vbox = QtGui.QVBoxLayout()
    vbox.addWidget(tableViewer0)
    mw.setLayout(vbox)
    mw.show()
    sys.exit(app.exec_())