【发布时间】:2021-08-16 19:29:27
【问题描述】:
我正在尝试通过 QProxyStyle 设置我的应用程序的样式。
我创建了一个 StyleCustom 类,它覆盖 drawControl 以根据标签状态将标签绘制为红色或绿色,并在其顶部添加文本。
但是,使用 option.text 会出现以下错误:
AttributeError: 'PySide2.QtWidgets.QStyleOption' object has no attribute 'text'
我注意到这里 option 是 QStyleOption 如果我没记错的话应该是 QStyleOptionTab。
如果我评论 drawText 命令,不会崩溃,但选项卡没有按应有的颜色显示:
我觉得不知何故,drawControl 方法没有正确接收选项。我在尝试绘制其他控件类型时注意到了类似的行为。
这是一个使用QTabWidget 的基本示例:
from PySide2 import QtWidgets, QtGui, QtCore
class StyleCustom(QtWidgets.QProxyStyle):
def drawControl(self, element: QtWidgets.QStyle.ControlElement, option: QtWidgets.QStyleOption, painter: QtGui.QPainter, widget:QtWidgets.QWidget=None):
if element == QtWidgets.QStyle.ControlElement.CE_TabBarTabLabel:
if option.state == QtWidgets.QStyle.State_Selected:
painter.save()
painter.fillRect(option.rect, QtGui.QBrush("#ff0000"))
painter.restore()
else:
painter.save()
painter.fillRect(option.rect, QtGui.QBrush("#00ff00"))
painter.restore()
painter.drawText(option.rect, QtCore.Qt.AlignCenter, option.text)
else:
return super().drawControl(element, option, painter, widget)
class MyMainWindow(QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
self.tab = QtWidgets.QTabWidget()
self.widg_1 = QtWidgets.QWidget()
self.widg_2 = QtWidgets.QWidget()
self.setCentralWidget(self.tab)
self.tab.addTab(self.widg_1, "test1")
self.tab.addTab(self.widg_2, "test2")
if __name__=='__main__':
app = QtWidgets.QApplication()
app.setStyle(StyleCustom())
window = MyMainWindow()
window.show()
app.exec_()
【问题讨论】: