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

30 投票
5 回答
119171 浏览
提问于 2025-04-18 12:40

我正在使用以下代码将 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 的背景颜色以及按钮文本的颜色。

5 个回答

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)");
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 窗口

0

我想给Trilarion的回答加个评论,但我的积分不够。

我按照他的建议操作,结果没有去掉边框,方法是:

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

在我的应用程序上先执行了.show()。我不太明白为什么先不行,后面就可以。如果有人能解释一下,那就太好了。

7

对于那些仍然想要通过指令来改变按钮颜色的人

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

但又无法做到的,只需把上面的指令修改为

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

这样就能改变按钮的颜色了,关键是要去掉边框。

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_()

这样做的结果是:

在这里输入图片描述

撰写回答