是否可以先创建一个ComboBox项,然后设置其显示属性(例如项目的背景颜色,图标,字体颜色,字体大小等等,然后使用Comobobox的.addItem()方法将其添加到ComboBox?因为现在我被困在使用:
myCombobox = QtGui.QComboBox
for i in range(10):
myCombobox.addItem(str(i))
毋庸置疑,这种方法几乎没有空间来定制各个ComboBox的项目显示属性。我想要的是这样的:
myCombobox = QtGui.QComboBox
for i in range(10):
item = comboboxItem()
item.setColor(allBlueAndShiny)
font = QtGui.QFont()
font.setPointSize(10)
item.setFont(font)
# Only after item was set with all display properties it is added:
myCombobox.addItem(str(i))
稍后编辑
以下是QCombobox定制项目的工作示例。谢谢Ekhumoro!
from PyQt4 import QtGui, QtCore
def main():
app = QtGui.QApplication(sys.argv)
window = QtGui.QWidget()
main_layout = QtGui.QVBoxLayout()
# QComboBox
combo = QtGui.QComboBox()
model = combo.model()
for row in range(10):
item = QtGui.QStandardItem(str(row))
item.setForeground(QtGui.QColor('red'))
font = item.font()
font.setPointSize(10)
item.setFont(font)
model.appendRow(item)
main_layout.addWidget(combo)
ok_button = QtGui.QPushButton("OK")
ok_button.clicked.connect(OK)
main_layout.addWidget(ok_button)
main_layout.addStretch(1)
window.setLayout(main_layout)
window.show()
sys.exit(app.exec_())
def OK(self):
print 'OK'
if __name__ == '__main__':
main()
答案 0 :(得分:7)
默认情况下,QComboBox
使用QStandardItemModel,因此QStandardItem方法可用于更改各种显示属性:
combo = QtGui.ComboBox()
model = combo.model()
for row in range(10):
item = QtGui.QStandardItem(str(index))
item.setForeground(QtGui.QColor('red'))
font = item.font()
font.setPointSize(10)
item.setFont(font)
model.appendRow(item)
<强> PS 强>:
如果您要重置其中一个item properties,请将其设置为None
,如下所示:
item = self.combo.model().item(row)
item.setData(None, QtCore.Qt.ForegroundRole)