我创建了一个QListWidget,并在其中填充了复选框,并且我想对它进行编码,使得如果检查了列表中的3个以上项目,则要检查的“第四”项目是文本颜色将变成红色。
当前,我遇到的问题是,一旦选中了第四项,所有文本都将变为红色,而我只希望第四(及以后)选中的项将变为红色,而不是全部。< / p>
这是我的代码:
class PromptDialog(QtGui.QDialog):
def __init__(self, items_list, parent=None):
super(PromptDialog, self).__init__(parent)
self.setWindowTitle("My Test Dialog")
self.init_ui(items_list)
self.init_connections()
def init_ui(self, items_list):
self.listWidget = QtGui.QListWidget()
for item in items_list:
list_widget_item = QtGui.QListWidgetItem(item)
# could be Qt.Unchecked; setting it makes the check appear
list_widget_item.setCheckState(QtCore.Qt.Unchecked)
self.listWidget.addItem(list_widget_item)
get_sels_btn = QtGui.QPushButton("Save Selections")
cancel_btn = QtGui.QPushButton("Cancel")
cancel_btn.clicked.connect(self.close)
hbox_layout = QtGui.QHBoxLayout()
hbox_layout.addWidget(self.listWidget, 1)
btns_layout = QtGui.QHBoxLayout()
btns_layout.addStretch(1)
btns_layout.addWidget(get_sels_btn)
btns_layout.addWidget(cancel_btn)
vbox_layout = QtGui.QVBoxLayout()
vbox_layout.addLayout(hbox_layout)
vbox_layout.addSpacing(12)
vbox_layout.addLayout(btns_layout)
self.setLayout(vbox_layout)
def init_connections(self):
self.listWidget.clicked.connect(self.derived_checked_opts)
def derived_checked_opts(self):
checked_items = []
for index in range(self.listWidget.count()):
if self.listWidget.item(index).checkState() == QtCore.Qt.Checked:
checked_items.append(self.listWidget.item(index))
if len(checked_items) > 3:
self.listWidget.setStyleSheet("color: red")
else:
self.listWidget.setStyleSheet("color: none")
some_items = ['item01', 'item02', 'item03', 'item04', 'item05', 'item06']
my_dialog = PromptDialog(some_items)
my_dialog.show()
我所期望的例子:
[x] item01
[x] item02
[x] item03
[] item04
[] item05
[] item06
[x] item01 --> Text remains white
[x] item02 --> Text remains white
[x] item03 --> Text remains white
[x] item04 --> Text will turns red
[] item05
[] item06
目前,我遇到的问题是案例2,所有文字都变成红色:
[x] item01 --> Text turns red
[x] item02 --> Text turns red
[x] item03 --> Text turns red
[x] item04 --> Text turns red
[] item05 --> Text turns red
[] item06 --> Text turns red