📌  相关文章
📜  PyQt5 - 将背景颜色设置为单选按钮的未选中指示器(1)

📅  最后修改于: 2023-12-03 15:18:46.951000             🧑  作者: Mango

PyQt5 - 将背景颜色设置为单选按钮的未选中指示器

在PyQt5中,可以使用QSS(Qt样式表)来设置单选按钮的样式,包括背景颜色、前景颜色、字体等等。其中,我们可以通过设置样式来将单选按钮的未选中指示器的背景颜色修改为我们想要的颜色。

下面是具体的实现方法:

代码实现
导入必要模块
from PyQt5.QtWidgets import QWidget, QRadioButton, QApplication
from PyQt5.QtCore import Qt
创建窗口和单选按钮
class MainWindow(QWidget):
    def __init__(self):
        super().__init__()
        self.setGeometry(100, 100, 300, 200)
        self.setStyleSheet("background-color: #FFFFFF;")
        
        self.radioButton1 = QRadioButton("Option 1", self)
        self.radioButton1.move(50, 50)
        self.radioButton1.setChecked(True)
        
        self.radioButton2 = QRadioButton("Option 2", self)
        self.radioButton2.move(50, 80)

在代码中,我们使用了PyQt5中的QWidget和QRadioButton控件来创建窗口和单选按钮。其中,QRadioButton默认的未选中指示器是圆形,而我们需要修改的就是这个圆形的背景颜色。

设置样式表
        self.radioButton1.setStyleSheet(
            "QRadioButton::indicator:!checked { background-color: red; border-color: red; }"
            "QRadioButton::indicator:checked { background-color: blue; border-color: blue; }"
        )
        
        self.radioButton2.setStyleSheet(
            "QRadioButton::indicator:!checked { background-color: green; border-color: green; }"
            "QRadioButton::indicator:checked { background-color: yellow; border-color: yellow; }"
        )

在以上代码中,我们使用了QSS来设置单选按钮的样式。其中,!checked表示未选中,checked表示选中。我们设置了未选中和选中的两种状态下,未选中指示器的背景颜色和边框颜色以及选中指示器的背景颜色和边框颜色。

完整代码
from PyQt5.QtWidgets import QWidget, QRadioButton, QApplication
from PyQt5.QtCore import Qt

class MainWindow(QWidget):
    def __init__(self):
        super().__init__()
        self.setGeometry(100, 100, 300, 200)
        self.setStyleSheet("background-color: #FFFFFF;")
        
        self.radioButton1 = QRadioButton("Option 1", self)
        self.radioButton1.move(50, 50)
        self.radioButton1.setChecked(True)
        
        self.radioButton2 = QRadioButton("Option 2", self)
        self.radioButton2.move(50, 80)
        
        self.radioButton1.setStyleSheet(
            "QRadioButton::indicator:!checked { background-color: red; border-color: red; }"
            "QRadioButton::indicator:checked { background-color: blue; border-color: blue; }"
        )
        
        self.radioButton2.setStyleSheet(
            "QRadioButton::indicator:!checked { background-color: green; border-color: green; }"
            "QRadioButton::indicator:checked { background-color: yellow; border-color: yellow; }"
        )

if __name__ == '__main__':
    app = QApplication([])
    window = MainWindow()
    window.show()
    app.exec_()

以上就是将PyQt5单选按钮的未选中指示器的背景颜色设置为我们想要的颜色的完整代码,欢迎尝试!