如何更改QPushButton的文本和背景颜色

30

我正在使用以下代码将QMenu连接到QPushButton。当按钮被点击时,会显示一个带有多个子菜单项的下拉菜单。

button=QPushButton()
button.setText("Press Me")

font=QtGui.QFont()
button.setFont(font)
button.setSizePolicy(ToolButtonSizePolicy)

button.setPopupMode(QtGui.QToolButton.InstantPopup)
menu=QtGui.QMenu()
button.setMenu(menu)

menuItem1=menu.addAction('Menu Item1')
menuItem2=menu.addAction('Menu Item2') 

现在根据条件,我想通过给QPushButton设置文本和背景颜色来自定义其显示。下面这行代码(用于更改背景颜色)对连接到QMenu的QPushButton没有任何影响。

button.setStyleSheet('QPushButton {background-color: #A3C1DA}')

我想知道如何更改QPushButton的背景颜色以及按钮文本的颜色。


您的代码存在一些不一致之处:ToolButtonSizePolicy未定义,只有QToolButtons具有setPopupMode,而QPushButtons没有。对于样式表,无论是QToolButton还是QPushButton都没有关系。您的样式表应该可以工作。 - Trilarion
5个回答

42

除了您的代码示例中存在一些不一致之外,设置QPushButton的背景颜色和文本颜色都可以正常工作:

setStyleSheet('QPushButton {background-color: #A3C1DA; color: red;}')

示例(使用 PySide):

from PySide import QtGui

app = QtGui.QApplication([])

button = QtGui.QPushButton()
button.setStyleSheet('QPushButton {background-color: #A3C1DA; color: red;}')
button.setText('Press Me')
menu = QtGui.QMenu()
menuItem1 = menu.addAction('Menu Item1')
menuItem2 = menu.addAction('Menu Item2')

button.setMenu(menu)
button.show()

app.exec_()

导致如下结果:

enter image description here


7
对于那些仍想使用指令更改按钮颜色的人:
button.setStyleSheet('QPushButton {background-color: #A3C1DA}')

如果无法完成此操作,只需修改上述指令为

button.setStyleSheet('QPushButton {background-color: #A3C1DA; border:  none}')

它将改变按钮的颜色,因此诀窍是去掉边框。


0

当鼠标悬停在按钮上时,更改背景颜色

self.button.setStyleSheet(
            "QPushButton::hover{"
            "background-color: #ffd2cf;"
            "border: none;"
            "}"
        )

你可以进一步改进你的按钮:

self.button.setToolTip("Hell o World")
self.button.mousePressEvent = lambda v: self.button.setIconSize(QSize(25, 25))#incresing iconsize
self.button.mouseReleaseEvent = lambda v: self.button.setIconSize(QSize(20, 20))#resetting to original iconsize
self.button.setStyleSheet(
    "QPushButton::hover{"
    "background-color: #ffd2cf;"
    "border: none;"
    "}"
)
self.button.myIcon = QIcon("c:/users/user-name/Pictures/icons/delete-row.png")
self.button.setIcon(self.button.myIcon)
self.button.setIconSize(QSize(20, 20))#setting original icon size

这是一个通用的 DecorableButton
from PySide6.QtWidgets import (QPushButton)
from PySide6.QtGui import (QIcon, QMouseEvent)
from PySide6.QtCore import (Qt, QSize)


class DecButton(QPushButton):
    def __init__(self, text: str = None, size: QSize = None, iconPath: str = None,
                 iconSize: QSize = None, onPressIconSizeIncrease: QSize = None,
                 onFocusBackgroundColor: str = None, toolTip: str = None, parent=None, color=None):

        super().__init__(parent=parent)
        ##initializing UI
        self.initUI(text=text, size=size, iconPath=iconPath,
                    iconSize=iconSize, onPressIconSizeIncrease=onPressIconSizeIncrease,
                    onFocusBackgroundColor=onFocusBackgroundColor, toolTip=toolTip, color=color)
        pass

    def initUI(self, text: str = None, size: QSize = None, iconPath: str = None,
               iconSize: QSize = None, onPressIconSizeIncrease: int = None,
               onFocusBackgroundColor: str = None, toolTip: str = None, color: str = None):

        if text is not None:
            self.setText(text)

        if size is not None:
            self.setFixedSize(size)

        if iconPath is not None:
            self.buttonIcon = QIcon(iconPath)
            self.setIcon(self.buttonIcon)

        self.buttonIconSize = iconSize
        if iconSize:
            self.setIconSize(self.buttonIconSize)

        self.onPressIconSizeIncrease = onPressIconSizeIncrease

        if onFocusBackgroundColor is not None:
            self.setStyleSheet(
                "QPushButton::hover{"
                f"background-color: {onFocusBackgroundColor};"
                "border: none;"
                "}"
            )
        if color is not None:
            if onFocusBackgroundColor is None:
                self.setStyleSheet(
                    "QPushButton{"
                    f"background-color: {color};"
                    "border: none;"
                    "}"
                )
            else:
                self.setStyleSheet(
                    "QPushButton{"
                    f"background-color: {color};"
                    "border: none;"
                    "}"
                    "QPushButton::hover{"
                    f"background-color: {onFocusBackgroundColor};"
                    "border: none;"
                    "}"
                )
        self.setToolTip(toolTip)

    def mousePressEvent(self, event: QMouseEvent) -> None:
        super().mousePressEvent(event)
        if self.onPressIconSizeIncrease:
            self.setIconSize(self.onPressIconSizeIncrease)

    def mouseReleaseEvent(self, event: QMouseEvent) -> None:
        super().mouseReleaseEvent(event)
        if self.onPressIconSizeIncrease:
            self.setIconSize(self.buttonIconSize)


if __name__ == "__main__":
    from PySide6.QtWidgets import (QApplication, QWidget, QVBoxLayout, QHBoxLayout)

    app = QApplication([])
    widget = QWidget()
    widget.layout = QHBoxLayout()
    widget.button = DecButton(iconPath="c:/users/devpa/Pictures/icons/delete-row.png",
                              iconSize=QSize(25, 25), onPressIconSizeIncrease=QSize(30, 30),
                              size=QSize(35, 35), onFocusBackgroundColor='#facdcd', color='#fcf8f7')
    widget.layout.addWidget(widget.button)
    widget.setLayout(widget.layout)
    widget.show()
    app.exec()

输出窗口:

DecorableButton Window


0

更改按钮文本:

from PyQt5.QtWidgets import QPushButton

button = QPushButton("Some text")
button.setText('New text')

修改按钮背景颜色:

from PyQt5.QtWidgets import QPushButton

button = QPushButton("Some text")
button1.setStyleSheet("background-color: red");

# or
# button2.setStyleSheet("background-color:#ff0000;");
# or
# button3.setStyleSheet("background-color:rgb(255,0,0)");

当我这样做时,按钮总是显示"新文本"? - Ben
如果你只想改变样式,只需使用.setStyleSheet()方法。我的答案实际上是针对给定问题的,这就是为什么我展示了更新文本的原因。 - Scott
实际上,我只想更改按钮上的文本。但是如描述的那样,它会立即通过“setText()”显示文本吗? - Ben
@Ben,是的,老兄)) - Scott

0

我想对Trilarions的回答添加评论,但是我的声望不够..

我能够使用他的建议,而不必移除边框

self.show() 
self.button.setStyleSheet('background-color: red;')

在我的应用程序上执行.show()之后。不确定为什么在之前不起作用。如果有人能解释一下那就太棒了。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接