Python 如何在pyqt中更改Qtablewidget的特定单元格背景颜色
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18889015/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to change Qtablewidget's specific cells background color in pyqt
提问by alperyazir
I am new in pyqt4 and I can't figure out how to do this. I have a QtableWidget with data in it. I want to change some background color of the tableWidget's cells.
我是 pyqt4 的新手,我不知道如何做到这一点。我有一个带有数据的 QtableWidget。我想更改 tableWidget 单元格的一些背景颜色。
I tried self.tableWidget.item(3, 5).setBackground(QtGui.QColor(100,100,150))
and it returns this error:
我试过了self.tableWidget.item(3, 5).setBackground(QtGui.QColor(100,100,150))
,它返回这个错误:
AttributeError: 'NoneType' object has no attribute 'setBackground'
AttributeError: 'NoneType' 对象没有属性 'setBackground'
What should I do?
我该怎么办?
采纳答案by hackyday
You must first create an item in that place in the table, before you can set its background color.
您必须先在表中的那个位置创建一个项目,然后才能设置其背景颜色。
self.tableWidget.setItem(3, 5, QtGui.QTableWidgetItem())
self.tableWidget.item(3, 5).setBackground(QtGui.QColor(100,100,150))
回答by Achayan
import sys
from PyQt4 import QtGui, QtCore
lista = ['aa', 'ab', 'ac']
listb = ['ba', 'bb', 'bc']
listc = ['ca', 'cb', 'cc']
mystruct = {'A':lista, 'B':listb, 'C':listc}
class MyTable(QtGui.QTableWidget):
def __init__(self, thestruct, *args):
QtGui.QTableWidget.__init__(self, *args)
self.data = thestruct
self.setmydata()
def setmydata(self):
n = 0
for key in self.data:
m = 0
for item in self.data[key]:
newitem = QtGui.QTableWidgetItem(item)
if key == 'A':
newitem.setBackground(QtGui.QColor(100,100,150))
elif key == 'B':
newitem.setBackground(QtGui.QColor(100,150,100))
else:
newitem.setBackground(QtGui.QColor(150,100,100))
self.setItem(m, n, newitem)
m += 1
n += 1
def main(args):
app = QtGui.QApplication(args)
table = MyTable(mystruct, 5, 3)
table.show()
sys.exit(app.exec_())
if __name__=="__main__":
main(sys.argv)
Slightly Modifiled version of http://www.saltycrane.com/blog/2006/10/qtablewidget-example-using-python-24/
http://www.saltycrane.com/blog/2006/10/qtablewidget-example-using-python-24/的略微修改版本