PyQt5 – 改变被按下的按钮的颜色

  • Post category:Python

要实现“PyQt5 – 改变被按下的按钮的颜色”,需要使用PyQt5的QPushButton组件。以下是实现步骤:

  1. 导入必要的库
from PyQt5.QtWidgets import QApplication, QPushButton
from PyQt5.QtGui import QColor
from PyQt5.QtCore import Qt
  1. 创建应用程序
app = QApplication([])
  1. 创建按钮并设置样式
button = QPushButton('click me')
button.setStyleSheet('background-color: blue')
  1. 定义按钮切换功能函数
def toggle():
    if button.styleSheet() == 'background-color: blue':
        button.setStyleSheet('background-color: red')
    else:
        button.setStyleSheet('background-color: blue')
  1. 将切换函数绑定到按钮点击事件上
button.clicked.connect(toggle)
  1. 显示窗口并启动应用程序,进入事件循环
button.show()
app.exec_()

在示例代码中,需要通过toggle()函数实现按钮颜色的切换。该函数检查当前按钮的样式表,如果当前背景色为蓝色,则将背景色改为红色,否则将背景色改为蓝色。

以下是事件循环中的完整代码示例:

from PyQt5.QtWidgets import QApplication, QPushButton
from PyQt5.QtGui import QColor
from PyQt5.QtCore import Qt

app = QApplication([])

button = QPushButton('click me')
button.setStyleSheet('background-color: blue')

def toggle():
    if button.styleSheet() == 'background-color: blue':
        button.setStyleSheet('background-color: red')
    else:
        button.setStyleSheet('background-color: blue')

button.clicked.connect(toggle)

button.show()
app.exec_()

使用该代码示例,每次点击按钮,按钮的背景颜色都会发生变化。

下面再提供一种实现方式,通过设置按钮是否按下的状态,来改变按钮的背景颜色。示例代码如下:

from PyQt5.QtWidgets import QApplication, QPushButton
from PyQt5.QtGui import QColor
from PyQt5.QtCore import Qt

app = QApplication([])

button = QPushButton('click me')
button.setStyleSheet('QPushButton:pressed {background-color: red} QPushButton {background-color: blue}')

button.show()
app.exec_()

在该代码中,我们通过设置样式表,来让按钮在被按下时显示红色背景,没有被按下时显示蓝色背景。可以通过修改样式表来改变按钮被按下和未被按下时的显示效果。