要实现从未选中的复选框为已按下的指示器设置背景图片,需要使用PyQt5中的QSS(Qt Style Sheet)来设置样式。以下是详细的使用攻略:
- 导入必要的依赖项
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QPixmap
from PyQt5.QtWidgets import QCheckBox, QApplication
- 创建自定义复选框类
class CustomCheckBox(QCheckBox):
def __init__(self):
super().__init__()
# 设置复选框的默认样式
self.setStyleSheet("QCheckBox::indicator {width: 20px; height: 20px;}");
- 重写paintEvent方法
def paintEvent(self, event):
# 绘制复选框指示器的背景
if self.isChecked():
bg_image = QPixmap('checked.png')
else:
bg_image = QPixmap('unchecked.png')
painter = QPainter(self)
painter.drawPixmap(0, 0, bg_image.width(), bg_image.height(), bg_image)
# 使用默认的绘制方法
super().paintEvent(event)
- 设置样式表
app = QApplication(sys.argv)
checkbox = CustomCheckBox()
checkbox.setStyleSheet(
"QCheckBox::indicator:checked {background-color: transparent;}"
"QCheckBox::indicator:unchecked {background-color: transparent;}"
)
在这里,我们使用了两个样式表来覆盖复选框指示器的背景为透明,否则会和背景图片冲突。
接下来是两个示例说明:
示例1:用PyQt5设置具有背景图片的复选框
app = QApplication(sys.argv)
checkbox = CustomCheckBox()
checkbox.setGeometry(50, 50, 100, 100)
checkbox.show()
app.setStyleSheet(
"QCheckBox::indicator:checked {background-color: transparent;}"
"QCheckBox::indicator:unchecked {background-color: transparent;}"
)
sys.exit(app.exec_())
示例2:用PyQt5为复选框应用动画
app = QApplication(sys.argv)
checkbox = CustomCheckBox()
checkbox.setGeometry(50, 50, 100, 100)
checkbox.show()
app.setStyleSheet(
"QCheckBox::indicator:checked {background-color: transparent;}"
"QCheckBox::indicator:unchecked {background-color: transparent;}"
"QCheckBox::indicator:checked {"
" border: 0px solid #2f9e99;"
" border-radius: 10px;"
" background-color: #2f9e99;"
" width: 20px;"
" height: 20px;"
"}"
"QCheckBox::indicator:checked:pressed {"
" background-color: #19ad9d;"
" border: 1px solid #19ad9d;"
"}"
"QCheckBox::indicator:hover {"
" border: 2px solid #19ad9d;"
"}"
)
animation1 = QPropertyAnimation(checkbox, b"geometry")
animation1.setDuration(500)
animation1.setStartValue(QRect(50, 50, 100, 100))
animation1.setEndValue(QRect(150, 50, 100, 100))
animation1.setEasingCurve(QEasingCurve.OutQuad)
animation2 = QPropertyAnimation(checkbox, b"geometry")
animation2.setDuration(500)
animation2.setStartValue(QRect(150, 50, 100, 100))
animation2.setEndValue(QRect(50, 50, 100, 100))
animation2.setEasingCurve(QEasingCurve.InQuad)
animation_group = QSequentialAnimationGroup()
animation_group.addAnimation(animation1)
animation_group.addAnimation(animation2)
animation_group.setLoopCount(-1)
animation_group.start()
sys.exit(app.exec_())
此示例使用了QPropertyAnimation和QSequentialAnimationGroup来实现动画效果。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:PyQt5 – 从未选中的复选框为已按下的指示器设置背景图片 - Python技术站