我可以使用样式表来设置 QPushButton 在单击或选中时的背景颜色。然而,检查的颜色并不像我设置的那样;它们包括一些光栅图案。
我使用的代码是:
import sys
from PySide2.QtWidgets import (
QMainWindow, QApplication, QPushButton,
)
from PySide2.QtCore import (
QSize,
)
class Window(QMainWindow):
def __init__(self, parent=None):
super().__init__(parent)
self.setMinimumSize(QSize(180, 110))
self.setWindowTitle('QPushButton Example')
button0 = QPushButton('Button 0', self)
button0.setCheckable(True)
button0.setStyleSheet(
"""QPushButton { background-color: lightgrey; }"""
"""QPushButton::checked { background-color: blue; }"""
"""QPushButton::pressed { background-color: blue; }"""
)
button0.resize(100, 32)
button0.move(50, 10)
button1 = QPushButton('Button 1', self)
button1.setCheckable(True)
button1.setStyleSheet(
"""QPushButton { background-color: lightgrey; }"""
"""QPushButton::checked { background-color: red; }"""
"""QPushButton::pressed { background-color: red; }"""
)
button1.resize(100, 32)
button1.move(50, 60)
def main():
app = QApplication(sys.argv)
window = Window()
window.show()
app.exec_()
if __name__ == "__main__":
main()
只要用鼠标点击按钮,我就得到正确的颜色:
当我按下按钮时(当我“检查”按钮时),我会得到奇怪的颜色:
如何获得为“选中”设置的实际颜色而不是此光栅图案?
这会起作用:
import sys
from PySide2.QtWidgets import (
QMainWindow, QApplication, QPushButton,
)
from PySide2.QtCore import (
QSize,
)
class Window(QMainWindow):
def __init__(self, parent=None):
super().__init__(parent)
self.setMinimumSize(QSize(180, 110))
self.setWindowTitle('QPushButton Example')
button0 = QPushButton('Button 0', self)
button0.setCheckable(True)
button0.setStyleSheet(
"""QPushButton { background-color: lightgrey; }"""
"""QPushButton:checked { background-color: blue; border: none;}"""
"""QPushButton:pressed { background-color: lightblue; border: none;}"""
)
button0.resize(100, 32)
button0.move(50, 10)
button1 = QPushButton('Button 1', self)
button1.setCheckable(True)
button1.setStyleSheet(
"""QPushButton { background-color: lightgrey; }"""
"""QPushButton:checked { background-color: red; border: none; }"""
"""QPushButton:pressed { background-color: pink; border: none; }"""
)
button1.resize(100, 32)
button1.move(50, 60)
def main():
app = QApplication(sys.argv)
window = Window()
window.show()
app.exec_()
if __name__ == "__main__":
main()