为什么我的QStyledItemDelegate无法设置QComboBox装饰的颜色并设置图标?

时间:2019-11-13 07:15:08

标签: python pyqt pyqt5

我需要绘制QComboBox子项颜色并设置图标,但是在我的代码中它无法正常工作?

代码:

from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtPrintSupport import *
from PyQt5.QtChart import *
import random

class ComboBoxDelegate(QStyledItemDelegate):
    def __init__(self):
        super().__init__()

    def createEditor(self, parent: QWidget, option: QStyleOptionViewItem, index: QModelIndex):
        editor = QComboBox(parent)
        editor.addItems(list('ABCEF'))

        return editor

    def setEditorData(self, editor: QComboBox, index: QModelIndex):
        value = index.data(Qt.EditRole)
        editor.setCurrentText(value)

        # set red
        editor.setItemData(index.row(), index.data(Qt.DecorationRole), Qt.DecorationRole)
        editor.setItemData(index.row(), index.data(Qt.BackgroundRole), Qt.BackgroundRole)

    def setModelData(self, editor: QComboBox, model: QAbstractItemModel, index: QModelIndex):
        value = editor.currentText()
        model.setData(index, value, Qt.EditRole)

        #set red
        model.setData(index, Qt.red, Qt.DecorationRole)
        model.setData(index, Qt.yellow, Qt.BackgroundRole)

    def updateEditorGeometry(self, editor: QComboBox, option: QStyleOptionViewItem, index: QModelIndex):
        editor.setGeometry(option.rect)

    def paint(self, painter: QPainter, option: QStyleOptionViewItem, index: QModelIndex):
        style_option = QStyleOptionComboBox()
        style_option.currentIcon = QIcon('./test.jpg')
        QApplication.style().drawComplexControl(QStyle.CC_ComboBox, style_option, painter)

        painter.save()
        painter.setPen(Qt.blue)
        painter.drawText(option.rect, option.displayAlignment, index.data())
        painter.restore()

class DemoA(QMainWindow):
    def __init__(self):
        super().__init__()
        self.init_ui()

    def init_ui(self):
        model = QStandardItemModel(4, 2)

        # data = np.random.randint(1, 100, (4, 6))
        # model = TableModel(data)

        delegate = ComboBoxDelegate()

        table = QTableView()
        table.setModel(model)
        table.setItemDelegate(delegate)

        self.setCentralWidget(table)

app = QApplication([])
demo = DemoA()
demo.show()
app.exec()

结果:
启动时是否需要像图中的A单元格一样打开所有单元格?

0 个答案:

没有答案