1

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

4

1 回答 1

1

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

试试这里的提示

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_())
于 2013-04-16T14:52:01.687 回答