【问题标题】:PyQt changing QPushButton background color without resetting stylePyQt 在不重置样式的情况下更改 QPushButton 背景颜色
【发布时间】:2016-06-05 21:39:27
【问题描述】:

我想在不更改/重置整个样式的情况下更改按钮的背景颜色和文本颜色。

目前,我正在使用这个:

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

但这会改变按钮的整体风格:

因为默认样式是这样的:

我想要这样的东西:

所以,如果我要更改操作系统,我希望它使用默认样式并且只更改背景颜色。

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

编辑

@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)

这给了我这个结果:

搜索给了我相同或相似的 sn-ps 代码,但没有按照我的预期执行。

编辑 2

我放弃了这个搜索并使用了样式表,重新构建了我认为合适的样式。

我仍然想知道......在 PyQt 中,是否有可能在仅更改小部件的某些部分的同时复制原生样式?

编辑 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()

【问题讨论】:

  • 用 QPalette 改变它而不是用 StyleSheet
  • QPalette 有一个按钮角色。我认为这应该可行。
  • 好像没有按钮角色。或者我至少找不到一个..

标签: python pyqt pyqt4


【解决方案1】:

我试过这个,它正在工作。我在 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)

【讨论】:

    【解决方案2】:

    这是一种愚蠢但可行的方法:

        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)
    

    【讨论】:

      【解决方案3】:

      使用this answer,我设法将组中的按钮颜色设置为浅蓝色,并将其他未选择的按钮重置为默认值。

      假设您的主窗口存储了默认调色板,您可以访问它并使用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()
      

      【讨论】:

        猜你喜欢
        • 2014-01-07
        • 2014-09-22
        • 2022-10-13
        • 1970-01-01
        • 1970-01-01
        • 2016-06-25
        • 1970-01-01
        • 2019-01-23
        • 1970-01-01
        相关资源
        最近更新 更多