gpt4 book ai didi

python - 在 Pyqt 的 qtable 中更改选定字符串的颜色

转载 作者:太空宇宙 更新时间:2023-11-04 05:59:51 27 4
gpt4 key购买 nike

我是 PyQt 编程新手,正在使用 qt4 设计器设计 GUI。在 GUI 中,我有一个表,当我按下一个按钮时,它会被填充一次。 GUI 如下图所示:

enter image description here

现在在表格中,我希望“status”列中的字符串被着色,即“checked”字符串为“green”,“not_checked”字符串为“red”

我该怎么做,我可以使用样式表吗?请帮我解决这个问题

最佳答案

我建议使用 QtGui.QItemDelegate 来委托(delegate)显示您的数据。您还可以在 QTableWidgetQTableView 中使用。在 QItemDelegate.paint (self, QPainter painter, QStyleOptionViewItem option, QModelIndex index) 方法中实现。

在该方法中,如果您的自定义字段中有列(在本例中为第 2 列),请使用您的自定义颜色对其进行绘制。并实现您的自定义 QtGui.QItemDelegate 完成,放入您的 QTableWidgetQTableView 通过使用 QAbstractItemView.setItemDelegate (self, QAbstractItemDelegate delegate)

例子;

import sys
from PyQt4 import QtGui, QtCore

class ENUM_STATUS:
CHECKED = QtCore.QString('checked')
NOT_CHECKED = QtCore.QString('not_checked')

class QCustomDelegate (QtGui.QItemDelegate):
def paint (self, painterQPainter, optionQStyleOptionViewItem, indexQModelIndex):
column = indexQModelIndex.column()
if column == 1:
textQString = indexQModelIndex.model().data(indexQModelIndex, QtCore.Qt.EditRole).toString()
if textQString == ENUM_STATUS.CHECKED:
currentQColor = QtCore.Qt.darkGreen
elif textQString == ENUM_STATUS.NOT_CHECKED:
currentQColor = QtCore.Qt.darkRed
else:
currentQColor = QtCore.Qt.darkGray
painterQPainter.setPen(currentQColor)
painterQPainter.drawText(optionQStyleOptionViewItem.rect, QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter, textQString)
else:
QtGui.QItemDelegate.paint(self, painterQPainter, optionQStyleOptionViewItem, indexQModelIndex)

class QCustomTableWidget (QtGui.QTableWidget):
def __init__ (self, parent = None):
super(QCustomTableWidget, self).__init__(parent)

### <! This is initiate your QTableWidget or QTableView, Your code >! ###
listsHorizontalHeaderItem = ['Name', 'Status']
self.setColumnCount(len(listsHorizontalHeaderItem))
for index in range(self.columnCount()):
self.setHorizontalHeaderItem(index, QtGui.QTableWidgetItem(listsHorizontalHeaderItem[index]))
listsData = [
['Mr. A', ENUM_STATUS.CHECKED],
['Mr. B', ENUM_STATUS.NOT_CHECKED],
['Mr. C', ENUM_STATUS.NOT_CHECKED],
['Mr. D', ENUM_STATUS.CHECKED],
['Mr. E', ENUM_STATUS.CHECKED]]
self.setRowCount(len(listsData))
for row in range(len(listsData)):
for column in range(len(listsData[row])):
self.setItem(row, column, QtGui.QTableWidgetItem(listsData[row][column]))
### <! End initiate >! ###

# After initiated, Your have to setup delegate to your QTableWidget or QTableView, Add line
self.myQCustomDelegate = QCustomDelegate()
self.setItemDelegate(self.myQCustomDelegate)

if __name__ == '__main__':
myQApplication = QtGui.QApplication(sys.argv)
myQCustomTableWidget = QCustomTableWidget()
myQCustomTableWidget.show()
sys.exit(myQApplication.exec_())

关于python - 在 Pyqt 的 qtable 中更改选定字符串的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25679387/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com