简体   繁体   English

PyQt 在不重置样式的情况下更改 QPushButton 背景颜色

[英]PyQt changing QPushButton background color without resetting style

I want to change a Button's background color and text color without changing/resetting the whole style.我想在不更改/重置整个样式的情况下更改按钮的背景颜色和文本颜色。

Currently, I'm using this:目前,我正在使用这个:

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

But that changes the whole style of the button:但这改变了按钮的整体风格:

在此处输入图像描述

Since the default style looks like this:由于默认样式如下所示:

在此处输入图像描述

I would like to have something like this:我想要这样的东西:

在此处输入图像描述

So, if I were to change OS, I want it to use default style and only change the background color.所以,如果我要更改操作系统,我希望它使用默认样式并且只更改背景颜色。

Can I do this without manually replicating the style?我可以在不手动复制样式的情况下做到这一点吗?

EDIT :编辑

@Controlix Thank you for pointing me in the right direction. @Controlix 感谢您为我指明正确的方向。 However, I can't seem to be able to change the background color.但是,我似乎无法更改背景颜色。

I'm only able to change the border and text color using:我只能使用以下方法更改边框和文本颜色:

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)

Which gives me this result:这给了我这个结果:

在此处输入图像描述

Searching gave me same or similar snippets of code that don't do what I expected it to do.搜索给了我相同或相似的代码片段,这些片段没有按照我的预期去做。

EDIT 2 :编辑 2

I gave up on this search and used style sheets, rebuilding the styles as I see fit.我放弃了这个搜索并使用了样式表,重建了我认为合适的样式。

I'm still wondering though... Is it possible, in PyQt, to replicate native style while changing only certain part of a widget?不过我仍然想知道......在 PyQt 中,是否有可能在仅更改小部件的某些部分的同时复制本机样式?

EDIT 3编辑 3

I tried:我试过:

    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)

But I got this error:但我得到了这个错误:

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

How can I access the button role?如何访问按钮角色? How is it called?怎么称呼?

Just in case you need it, here is the DownloadButton class:以防万一您需要它,这里是 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()

I tried this which is working.我试过这个是有效的。 I have set the buttons styles in the UI section.我已经在 UI 部分设置了按钮样式。 if I want to change only the color of a button the following works.如果我只想更改按钮的颜色,则以下有效。

The following works though not an elegant way :以下工作虽然不是一种优雅的方式:

        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)

Here is a silly but working way to do it:这是一种愚蠢但有效的方法:

    def change_button_color(button, color):
        """change_button_color

            Change a button's color
        :param button: target button
        :type button: QPushButton
        :param color: new color (any format)
        :type color: str
        :return: None
        """
        style_sheet = button.styleSheet()
        pairs = [pair.replace(' ', '') for pair in style_sheet.split(';') if pair]

        style_dict = {}
        for pair in pairs:
            key, value = pair.split(':')
            style_dict[key] = value

        style_dict['background-color'] = color
        style_sheet = '{}'.format(style_dict)

        chars_to_remove = ('{', '}', '\'')
        for char in chars_to_remove:
            style_sheet = style_sheet.replace(char, '')
        style_sheet = style_sheet.replace(',', ';')

        button.setStyleSheet(style_sheet)

With this answer I managed to set the color of a button from a group to lightblue and reset the other not selected ones back to default.有了这个答案,我设法将一组按钮的颜色设置为浅蓝色,并将其他未选择的按钮重置为默认值。

Assuming that your main window stores the default palette, you can just access it and use it using self.palette().button().color() to set the color of your button to default again.假设您的主窗口存储了默认调色板,您可以访问它并使用self.palette().button().color()再次将按钮的颜色设置为默认值。

# Reset to default colors
for btn in self.btn_group.buttons():
    pal = btn.palette()
    pal.setColor(QPalette.Button, self.palette().button().color())
    btn.setPalette(pal)
    btn.update()
        
# Except for selected button
btn = self.btn_group.checkedButton()
pal = btn.palette()
pal.setColor(QPalette.Button, QColor.fromRgb(173, 216, 230))
btn.setPalette(pal)
btn.update()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM