PyQt改变QPushButton的背景颜色而不重置样式

问题描述 投票:0回答:1

我想在不改变整个样式的情况下改变Button的背景色和文字色。

目前,我正在使用这个方法。

dl_btt.setStyleSheet("background-color: green; color: white")

但是这样会改变按钮的整体风格。

enter image description here

因为默认的样式是这样的

enter image description here

我希望能有这样的风格

enter image description here

所以,如果我换了操作系统,我想让它使用默认样式,只改变背景颜色。

我可以在不手动复制样式的情况下做到这一点吗?

EDIT:

@Controlix 谢谢你给我指出了正确的方向。然而,我似乎无法改变背景颜色。

我只能够用 "改变 "来改变边框和文字的颜色。

dl_btt = DownloadButton(self, "Skini")

#dl_btt.setStyleSheet("background-color: green; color: white")
#dl_btt.setPalette(QtGui.QPalette(QtCore.Qt.green))

palette = dl_btt.palette()

role = dl_btt.foregroundRole()
palette.setColor(role, QtGui.QColor('white'))

role = dl_btt.backgroundRole()
palette.setColor(role, QtGui.QColor('green'))

dl_btt.setAutoFillBackground(True)
dl_btt.setPalette(palette)

得到的结果是这样的

enter image description here

搜索到的都是相同或相似的代码 但都没有达到我预期的效果。

EDIT 2:

我放弃了这个搜索,使用样式表,按照自己的想法重建样式。

但我还是想知道... 在PyQt中,是否有可能在复制原生样式的同时,只改变widget的某些部分?

EDIT 3

我试过了。

    palette = dl_btt.palette()
    role = dl_btt.foregroundRole()
    palette.setColor(role, QtGui.QColor('white'))

    role = dl_btt.buttonRole()
    palette.setColor(role, QtGui.QColor('green'))

    dl_btt.setAutoFillBackground(True)
    dl_btt.setPalette(palette)

但我得到了这个错误。

AttributeError: 'DownloadButton' object has no attribute 'buttonRole'

我怎么能访问按钮角色?如何调用它?

以防万一,这里是DownloadButton类。

class DownloadButton(QtGui.QPushButton):
    def __init__(self, master, *args, **kwargs):
        super(DownloadButton, self).__init__(*args, **kwargs)
        self.master = master

    def mousePressEvent(self, ev):
        self.master.startDownload()
pyqt4
1个回答
0
投票

我试了一下这个方法,效果很好,我把按钮的样式设置在了dl_btt.setStyleSheet("background-color: green; color: white")。我已经在UI部分设置了按钮的样式,如果我只想改变一个按钮的颜色,下面的方法就可以了。

下面的工作,虽然不是一个优雅的方式。

        btns = ['self.hBeamBtn','self.lBeamBtn','self.allTestBtn','self.prnStatusBtn']
        for btn in btns:
            if  str(btn_name) == str(btn):
                styl = btn+'.setStyleSheet("font: bold;background-color: red;font-size: 12px;height: 28px;width: 80px;")'
                eval(styl)
© www.soinside.com 2019 - 2024. All rights reserved.