如何更改 QPushButton 文本和背景颜色 [英] How to change QPushButton text and background color

查看:281
本文介绍了如何更改 QPushButton 文本和背景颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用以下代码将 QMenu 连接到 QPushButton.单击按钮时,会显示包含多个子菜单项的下拉菜单.

I am using following code to connect QMenu to QPushButton. When button is clicked a pull-down menu with multiple sub-menu's items is shown.

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 没有影响.

Now depending on a condition I would like to customize QPushButton display by giving it a text and background color. The following line of code (which is supposed to change background color) has no effect on QPushButton connected to QMenu.

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

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

I would like to know how to change the background color of QPushButton as well as button's text's color.

推荐答案

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

Apart from some inconsistencies with your code example setting the background color and text color of a QPushButton works just fine with:

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

示例(使用 PySide):

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

结果:

这篇关于如何更改 QPushButton 文本和背景颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆