[英]How to add background color to a specific dropdown from combobox in pyqt4
cbo.setStyleSheet('background-color: rgb(205,92,92)')
這會將背景添加到整個組合框。 我想將背景色添加到組合框的某些行。 謝謝
Qt有一個內部模型(QStandardItemModel),允許您通過setItemData()
設置每個項目的顏色:
index = 2
cbo.setItemData(index, QtGui.QColor(205, 92, 92), QtCore.Qt.BackgroundRole)
QComboBox的visible元素不是下拉菜單的一部分,因此它們將不會共享默認顏色,一種可能的解決方案是使用模型信息來更改QPalette:
class ComboBox(QtGui.QComboBox):
def __init__(self, parent=None):
super(ComboBox, self).__init__(parent)
self.currentIndexChanged[int].connect(self._on_currentIndexChanged)
self.model().dataChanged.connect(self._on_currentIndexChanged)
def _on_currentIndexChanged(self):
index = self.currentIndex()
pal = self.palette()
color = cbo.itemData(index, QtCore.Qt.BackgroundRole)
if color is None:
color = pal.color(QtGui.QPalette.Button)
cbo.setItemData(index, color, QtCore.Qt.BackgroundRole)
else:
pal.setColor(QtGui.QPalette.Button, color)
self.setPalette(pal)
例:
import random
from PyQt4 import QtCore, QtGui
class ComboBox(QtGui.QComboBox):
def __init__(self, parent=None):
super(ComboBox, self).__init__(parent)
self.currentIndexChanged[int].connect(self._on_currentIndexChanged)
self.model().dataChanged.connect(self._on_currentIndexChanged)
def _on_currentIndexChanged(self):
index = self.currentIndex()
pal = self.palette()
color = cbo.itemData(index, QtCore.Qt.BackgroundRole)
if color is None:
color = pal.color(QtGui.QPalette.Button)
cbo.setItemData(index, color, QtCore.Qt.BackgroundRole)
else:
pal.setColor(QtGui.QPalette.Button, color)
self.setPalette(pal)
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
w = QtGui.QWidget()
lay = QtGui.QVBoxLayout(w)
cbo = ComboBox()
cbo.addItems(["one", "two", "three", "four", "five"])
indexes = random.sample(range(cbo.count()), 3)
for index in indexes:
color = QtGui.QColor(*random.sample(range(255), 3))
cbo.setItemData(index, color, QtCore.Qt.BackgroundRole)
lay.addWidget(cbo)
lay.addWidget(QtGui.QTextEdit())
w.show()
sys.exit(app.exec_())
要將顏色添加到pyqt4中cbo(組合框)的特定索引行中:
cbo.model().item(index).setForeground(QtGui.QColor("green"))
cbo.model().item(index).setBackground(QtGui.QColor("red"))
若要顯示cbo關閉時單擊的cbo行文本的顏色:
color = cbo.model().item(index).foreground().color().getRgb() #index is index that was clicked
cbo.setStyleSheet("QComboBox:editable{{ color: rgb{} }}".format(color))
如果需要硬編碼,則:
cbo.setStyleSheet("QComboBox:editable{{ color: {} }}".format('red'))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.