为什么编辑器的背景是白色的,而油漆是灰色的?

Why is the background of the editor white but gray in paint?

我不知道为什么 paint 和 createEditor 看起来不一样。 它的大小和颜色略有不同。 我希望两者显示相同的大小和颜色。

from PySide2 import QtWidgets, QtCore, QtGui


class TestDelegate(QtWidgets.QStyledItemDelegate):

    def __init__(self, parent=None):
        super(TestDelegate, self).__init__(parent)

    def paint(self, painter, option, index):
        wid = QtWidgets.QWidget()
        layout = QtWidgets.QHBoxLayout(wid)
        btn = QtWidgets.QPushButton()
        layout.addWidget(btn)
        wid.setAutoFillBackground(True)

        painter.save()
        painter.translate(option.rect.topLeft())
        wid.resize(option.rect.size())
        wid.render(painter, QtCore.QPoint(0, 0))
        painter.restore()
    
    def createEditor(self, parent, option, index):
        wid = QtWidgets.QWidget(parent)
        layout = QtWidgets.QHBoxLayout(wid)
        btn = QtWidgets.QPushButton()
        layout.addWidget(btn)
        wid.setAutoFillBackground(True)
        return wid

if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)
    
    table = QtWidgets.QTableWidget(4,4)
    table.setItemDelegate(TestDelegate())
    table.show()
    sys.exit(app.exec_())

分享我找到的解决方案。

from PySide2 import QtWidgets, QtCore, QtGui


class TestDelegate(QtWidgets.QStyledItemDelegate):

    def __init__(self, parent=None):
        super(TestDelegate, self).__init__(parent)

    def paint(self, painter, option, index):
        wid = QtWidgets.QWidget()
        layout = QtWidgets.QHBoxLayout(wid)
        btn = QtWidgets.QPushButton()
        layout.addWidget(btn)
        wid.setAutoFillBackground(True)
        painter.save()
        painter.translate(option.rect.topLeft())
        wid.resize(option.rect.size())
        wid.setBackgroundRole(QtGui.QPalette.ColorRole.Base) # <<<<<<<<<<<
        wid.render(painter, QtCore.QPoint(0, 0))
        painter.restore()
    
    def createEditor(self, parent, option, index):
        wid = QtWidgets.QWidget(parent=parent)
        layout = QtWidgets.QHBoxLayout(wid)
        btn = QtWidgets.QPushButton()
        layout.addWidget(btn)
        wid.setAutoFillBackground(True)
        wid.setContentsMargins(2, 2, 2, 2)
        return wid

if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)
    
    table = QtWidgets.QTableWidget(4,4)
    table.setItemDelegate(TestDelegate())
    table.show()
    sys.exit(app.exec_())