Возможное решение - переписать делегатский метод initStyleOption()
:
from PySide2 import QtCore, QtGui, QtWidgets
class IconCenterDelegate(QtWidgets.QStyledItemDelegate):
def initStyleOption(self, option, index):
super(IconCenterDelegate, self).initStyleOption(option, index)
option.decorationAlignment = (
QtCore.Qt.AlignHCenter | QtCore.Qt.AlignCenter
)
option.decorationPosition = QtWidgets.QStyleOptionViewItem.Top
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
w = QtWidgets.QTreeView()
model = QtGui.QStandardItemModel(w)
w.setModel(model)
delegate = IconCenterDelegate(w)
w.setItemDelegateForColumn(1, delegate)
icons = [
"SP_TitleBarMinButton",
"SP_TitleBarMenuButton",
"SP_TitleBarMaxButton",
"SP_TitleBarCloseButton",
"SP_TitleBarNormalButton",
"SP_TitleBarShadeButton",
"SP_TitleBarUnshadeButton",
"SP_TitleBarContextHelpButton",
"SP_MessageBoxInformation",
"SP_MessageBoxWarning",
"SP_MessageBoxCritical",
"SP_MessageBoxQuestion",
"SP_DesktopIcon",
]
parent = model.invisibleRootItem()
for icon_name in icons:
icon = QtWidgets.QApplication.style().standardIcon(
getattr(QtWidgets.QStyle, icon_name)
)
its = []
for _ in range(3):
it = QtGui.QStandardItem()
it.setIcon(icon)
its.append(it)
parent.appendRow(its)
model.appendRow(it)
w.resize(640, 480)
w.expandAll()
w.show()
sys.exit(app.exec_())
Если вы хотите, чтобы значки всех столбцов выравнивались по центру, вы можете перезаписать метод viewOptions () представления:
class TreeView(QtWidgets.QTreeView):
def viewOptions(self):
option = super().viewOptions()
option.decorationAlignment = (
QtCore.Qt.AlignHCenter | QtCore.Qt.AlignCenter
)
option.decorationPosition = QtWidgets.QStyleOptionViewItem.Top
return option