如何更改QP的当前颜色组

2024-09-10 21:40:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图更改qpalete的当前颜色组,但是qpalete的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_()

这是我得到的输出:

^{pr2}$

所以。。。似乎setCurrentColorGroup什么也不做。关于如何改变当前的颜色组有什么想法吗?

提前谢谢!

(顺便说一句,我在Windows7系统上运行的是Pyside1.2.4和Qt4.8)


Tags: 方法代码app颜色sysbuttonprintqtgui
1条回答
网友
1楼 · 发布于 2024-09-10 21:40:14

似乎您正在尝试更改图标的呈现方式,而不是小部件的绘制方式,因此调色板不是正确使用的API。相反,您应该使用QIcon,它允许不同的图像用于不同的modes和{a3}。在

要在NormalDisabled模式中使用相同的图像,可以使用如下代码:

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文档中的警告:

Custom icon engines are free to ignore additionally added pixmaps.

因此,不能保证这将适用于所有平台上的所有widget样式。在

更新

如果上面的方法不起作用,可能意味着小部件样式正在控制禁用图标的呈现方式。相关的QStyleAPI是generatedIconPixmap,它返回根据icon mode和样式选项修改的pixmap的副本。似乎这个方法有时也会考虑到调色板(与我上面所说的有些相反),但是当我测试这个方法时,它没有任何影响。我这样重置调色板:

^{pr2}$

当按钮被禁用时,颜色看起来很正常,但是图标仍然是灰色的。不过,您可能会想尝试一下,以防在您的平台上出现不同的情况(如果不这样做,请不要惊讶)。在

控制图标禁用的正确方法似乎是创建一个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_())

相关问题 更多 >