PyQt5中设置禁用复选框选中状态背景色的问题
Hey there, let's sort out this issue with your QCheckBox where you can't change the background color when it's checked, even though you've made it non-interactive via WA_TransparentForMouseEvents and NoFocus. The root problem here is that Qt's default styles have higher priority for certain control states—like checked—and your basic background-color setting gets overridden, especially since the checkbox is inside a table widget.
Here are two stylesheet-based fixes that don't require any signal-slot work, which is exactly what you're looking for:
Option 1: Explicitly Style the Checked State
Just add the :checked pseudo-state to your stylesheet to make sure the background color applies when the box is checked. Update your checkbox's stylesheet code to this:
self.tableWidget.checkBox.setStyleSheet(""" QCheckBox:checked { background-color: white; } QCheckBox { background-color: white; padding-left: 10px; } """)
By explicitly defining the style for the checked state, you're overriding Qt's default drawing logic for that state. This ensures your background color sticks even when the box is selected.
Option 2: Match "Disabled + Checked" State (For Visual Clarity)
If you want the checkbox to visually look disabled (since users can't interact with it) while still keeping your custom checked background color, you can switch to using setEnabled(False) instead of those mouse/focus attributes, then target the :disabled:checked compound pseudo-state:
# Replace your existing attribute settings with this to disable the checkbox self.tableWidget.checkBox.setEnabled(False) # Update the stylesheet to target disabled and checked states self.tableWidget.checkBox.setStyleSheet(""" QCheckBox:disabled:checked { background-color: white; } QCheckBox:disabled { background-color: white; padding-left: 10px; } """)
This approach aligns with Qt's native state handling, making your styles more predictable. The compound pseudo-state ensures the background color applies only when the box is both disabled and checked.
Why Your Original Code Didn't Work
Your initial stylesheet only set the background color for the checkbox's default state. Qt's built-in QCheckBox style has specific rules for the checked state that take precedence over your general background setting. By adding the :checked (or :disabled:checked) pseudo-state to your stylesheet, you're giving your custom style higher priority than the default one.
Also, since the checkbox is inside a QTableWidget, the table's stylesheet can sometimes leak down to child widgets—but targeting the specific pseudo-states for the checkbox avoids that issue entirely.
内容的提问来源于stack exchange,提问作者Sherief El-Ghazawi

