PyQt5 – 改变单选按钮在悬停状态下的颜色

  • Post category:Python

要改变PyQt5中单选按钮在悬停状态下的颜色,可以通过QStyleSheet实现。具体步骤如下:

  1. 在PyQt5中为单选按钮定义样式:
self.radioButton.setStyleSheet("QRadioButton:hover {color: blue}")

这个样式表表示:当鼠标悬停在单选按钮上时,该单选按钮显示为蓝色。

  1. 在PyQt5中为单选按钮定义样式表并将其应用于整个应用程序:
app.setStyleSheet("QRadioButton:hover {color: blue}")

这个样式表表示:当鼠标悬停在任何单选按钮上时,该单选按钮显示为蓝色。

示例1:

下面是一个简单的单选按钮示例,当鼠标悬停在单选按钮上时,背景颜色将变成浅蓝色:

import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QRadioButton


class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        # 创建一个单选按钮
        self.radioButton = QRadioButton("RadioButton", self)
        self.radioButton.setGeometry(50, 50, 150, 30)

        # 为单选按钮定义样式
        self.radioButton.setStyleSheet("QRadioButton:hover {background-color: lightblue}")

if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())

示例2:

下面是一个更复杂的示例。我们创建了三个单选按钮,在鼠标悬停时它们的文本颜色分别会变成红色、绿色和蓝色:

import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QRadioButton, QHBoxLayout, QWidget, QLabel


class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        # 创建三个单选按钮
        self.radioButton1 = QRadioButton("RadioButton1")
        self.radioButton1.setStyleSheet("QRadioButton:hover {color: red}")
        self.radioButton2 = QRadioButton("RadioButton2")
        self.radioButton2.setStyleSheet("QRadioButton:hover {color: green}")
        self.radioButton3 = QRadioButton("RadioButton3")
        self.radioButton3.setStyleSheet("QRadioButton:hover {color: blue}")

        # 创建一个容器窗口和一个水平布局
        widget = QWidget()
        layout = QHBoxLayout(widget)

        # 将三个单选按钮添加到水平布局
        layout.addWidget(self.radioButton1)
        layout.addWidget(self.radioButton2)
        layout.addWidget(self.radioButton3)

        # 将水平布局设置为主窗口的中央窗口
        self.setCentralWidget(widget)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())

此时,当鼠标悬停在RadioButton1时,RadioButton1文本会变成红色;当鼠标悬停在RadioButton2时,RadioButton2文本会变成绿色;当鼠标悬停在RadioButton3时,RadioButton3文本会变成蓝色。