所以我试图根据item.text()为QTableWidget QTableWidgetItems着色。这是我的代码:
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
import sys
class Table(QTableWidget):
def __init__(self, parent):
super(Table, self).__init__(parent)
self.setColumnCount(9)
self.setRowCount(1)
self.setItem(0, 0, QTableWidgetItem('A'))
self.setItem(0, 1, QTableWidgetItem('B'))
self.setItem(0, 2, QTableWidgetItem('C'))
self.setItem(0, 3, QTableWidgetItem('D'))
self.setItem(0, 4, QTableWidgetItem('E'))
self.setItem(0, 5, QTableWidgetItem('F'))
self.setItem(0, 6, QTableWidgetItem('A'))
self.setItem(0, 7, QTableWidgetItem('C'))
self.setItem(0, 8, QTableWidgetItem('D'))
for r in range(self.rowCount()):
for c in range(self.columnCount()):
item = QTableWidgetItem()
self.item(r, c).setBackground(self.colour(self.item(r, c).text()))
def colour(self, letter):
if letter == 'A':
colour = QColor(233, 12, 24)
if letter == 'B':
colour = QColor(12, 45, 67)
if letter in ['C', 'E']:
colour = QColor(23, 57, 188)
if letter == 'F':
colour = QColor(45, 116, 75)
else:
colour = QColor(233, 244, 12)
return colour
def main():
app = QApplication(sys.argv)
window = QWidget()
window.setGeometry(200,200,1200,400)
tw = Table(window)
twLayout = QVBoxLayout()
twLayout.addWidget(tw)
window.setLayout(twLayout)
window.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
运行它时,表中只有两种颜色,其余的都会被忽略。如何修复它,如何确保每个单元格根据其内容获得其单独的颜色?
答案 0 :(得分:0)
在Table.colour
的定义中,您有多个if
语句,但是else
子句将仅匹配其中的最后一个。你想要...
def colour(self, letter):
if letter == 'A':
colour = QColor(233, 12, 24)
elif letter == 'B':
colour = QColor(12, 45, 67)
elif letter in ['C', 'E']:
colour = QColor(23, 57, 188)
elif letter == 'F':
colour = QColor(45, 116, 75)
else:
colour = QColor(233, 244, 12)
return colour