pyqt checkbox 怎么设置背景色和前景色?
时间: 2023-11-01 11:09:49 浏览: 40
你可以使用QSS(Qt样式表)来设置PyQt中的checkbox的背景色和前景色。
以下是示例代码:
```python
from PyQt5.QtWidgets import QApplication, QCheckBox, QWidget
from PyQt5.QtCore import Qt
class Example(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.setGeometry(300, 300, 250, 150)
self.setWindowTitle('Checkbox')
cb = QCheckBox('Show title', self)
cb.move(20, 20)
cb.toggle()
cb.setStyleSheet('QCheckBox::indicator {background-color: red; border: 1px solid black;}'
'QCheckBox::indicator:checked {background-color: blue;}')
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
```
在上面的示例中,我们使用了`setStyleSheet()`函数来设置QCheckBox的样式。我们使用了两个伪状态选择器:
- `QCheckBox::indicator`:用于设置checkbox的外观,包括背景色和边框颜色。
- `QCheckBox::indicator:checked`:用于设置checkbox选中时的背景色。
可以根据需要更改颜色值。