我试图改变当前的颜色组论坛QPalette,但似乎QPalette的setCurrentColorGroup方法根本不起作用。
我正在运行这个代码:
app = QtGui.QApplication(sys.argv) button = QPushButton() svgWidget = QSvgWidget(resources_paths.getPathToIconFile("_playableLabels/42-labelPlay-disabled-c.svg")) button.setLayout(QHBoxLayout()) button.layout().addWidget(svgWidget) button.setFixedSize(QSize(300, 300)) print button.palette().currentColorGroup() button.setEnabled(False) print button.palette().currentColorGroup() button.palette().setCurrentColorGroup(QPalette.ColorGroup.Normal) print button.palette().currentColorGroup() button.show() print button.palette().currentColorGroup() app.exec_()
这是我得到的输出:
PySide.QtGui.QPalette.ColorGroup.Normal PySide.QtGui.QPalette.ColorGroup.Disabled PySide.QtGui.QPalette.ColorGroup.Disabled PySide.QtGui.QPalette.ColorGroup.Disabled Process finished with exit code -1
所以…看来,setCurrentColorGroup什么也没有。 有关如何更改当前颜色组的任何想法?
提前致谢!
(顺便说一下,我在Windows 7系统上运行PySide 1.2.4和Qt 4.8)
看起来,你正试图改变图标的呈现方式,而不是小部件的绘制方式,所以调色板不是正确的API使用。 相反,你应该使用一个QIcon ,它允许不同的图像被用于各种模式和状态 。
要在Normal
和Disabled
模式下使用相同的图像,您可以使用如下代码:
icon = QtGui.QIcon() icon.addPixmap(QtGui.QPixmap('image.svg'), QtGui.QIcon.Normal) icon.addPixmap(QtGui.QPixmap('image.svg'), QtGui.QIcon.Disabled) button = QtGui.QPushButton() button.setIcon(icon)
但是,您应该仔细注意Qt文档中的这个警告:
自定义图标引擎可以自由地忽略额外添加的像素图。
因此,不能保证这将适用于所有平台上的所有窗口小部件样式。
更新 :
如果上述方法不起作用,这可能意味着小部件样式正在控制如何呈现禁用的图标。 相关的QStyle
API是generatedIconPixmap ,它返回根据图标模式和样式选项修改的pixmap的副本。 看来这种方法有时也会考虑调色板(与上面所述的有些相反),但是当我测试这个时,它没有任何影响。 我像这样重置调色板:
palette = self.button.palette() palette.setCurrentColorGroup(QtGui.QPalette.Normal) palette.setColorGroup(QtGui.QPalette.Disabled, palette.windowText(), palette.button(), palette.light(), palette.dark(), palette.mid(), palette.text(), palette.brightText(), palette.base(), palette.window(), ) button.setPalette(palette)
当按钮被禁用时,这使得颜色看起来很正常 – 但是图标仍然是灰色的。 不过,如果在平台上的工作方式不同,你可能会想尝试一下(如果他们不这样做,不要感到惊讶)。
看来控制禁用图标的正确方法是创建一个QProxyStyle
并覆盖generatedIconPixmap
方法。 不幸的是,这个类在PyQt4中是不可用的,但是我已经在PyQt5中测试过了,它工作正常。 所以我目前唯一的工作解决方案是升级到PyQt5,并使用QProxyStyle
。 这是一个演示脚本,演示如何实现它:
import sys from PyQt5 import QtCore, QtGui, QtWidgets class ProxyStyle(QtWidgets.QProxyStyle): def generatedIconPixmap(self, mode, pixmap, option): if mode == QtGui.QIcon.Disabled: mode = QtGui.QIcon.Normal return super(ProxyStyle, self).generatedIconPixmap( mode, pixmap, option) class Window(QtWidgets.QWidget): def __init__(self): super(Window, self).__init__() self.button = QtWidgets.QPushButton(self) self.button.setIcon(QtGui.QIcon('image.svg')) self.button2 = QtWidgets.QPushButton('Test', self) self.button2.setCheckable(True) self.button2.clicked.connect(self.button.setDisabled) layout = QtWidgets.QVBoxLayout(self) layout.addWidget(self.button) layout.addWidget(self.button2) if __name__ == '__main__': app = QtWidgets.QApplication(sys.argv) app.setStyle(ProxyStyle()) window = Window() window.setGeometry(600, 100, 300, 200) window.show() sys.exit(app.exec_())