如何为可勾选QListWidgetItem的复选框设置边框颜色?
Got it, let's sort out that checkbox border color issue for your QListWidget items. The problem with your initial stylesheet is that you were targeting the entire QListWidget::item, which affects the whole list item's background and borders. Instead, we need to zero in on just the checkbox part of the list item—Qt calls this the indicator for checkable items.
Here's the Solution
Use the QListWidget::indicator pseudo-element in your stylesheet to style only the checkbox. This way, you won't alter the list item's background, and you can set the checkbox border exactly how you want.
First, keep your existing code for creating checkable items (the setForeground part still works for text color):
watch_list = ["Protesters", "Local news staff", "Techfluencers"] for category in watch_list: item = QtWidgets.QListWidgetItem(category) item.setFlags(item.flags() | QtCore.Qt.ItemIsUserCheckable) item.setCheckState(QtCore.Qt.Unchecked) item.setForeground(QtGui.QColor('#FFFFFF')) # Keeps text white self.watchListslistWidget.addItem(item)
Then apply this stylesheet to your QListWidget—adjust the background color to match your original UI (I used a dark gray example, but replace it with whatever you need):
QListWidget { background-color: #2b2b2b; /* Match your original background here */ } QListWidget::indicator { border: 1px solid #FFFFFF; /* This sets the checkbox border color */ width: 13px; /* Optional: Adjust checkbox size */ height: 13px; border-radius: 2px; /* Optional: Add rounded corners to the checkbox */ } QListWidget::indicator:checked { background-color: #FFFFFF; /* Optional: Fill color when checkbox is checked */ border: 1px solid #FFFFFF; /* Keep border white when checked */ } QListWidget::indicator:unchecked { background-color: transparent; /* Leave background transparent when unchecked */ }
To apply it in code:
self.watchListslistWidget.setStyleSheet(""" QListWidget { background-color: #2b2b2b; } QListWidget::indicator { border: 1px solid #FFFFFF; width: 13px; height: 13px; border-radius: 2px; } QListWidget::indicator:checked { background-color: #FFFFFF; border: 1px solid #FFFFFF; } QListWidget::indicator:unchecked { background-color: transparent; } """)
Why This Works
QListWidget::indicatorspecifically targets the checkbox icon inside each list item, so your styles only affect that small element.- Setting
background-coloronQListWidgetensures the main list background stays as you want it, instead of getting overridden accidentally. - You can tweak the
width,height, andborder-radiusvalues to match your UI's design.
内容的提问来源于stack exchange,提问作者B.Obilo

