我有一个带有QListWidget的表单,我在其中重复添加新项目。除了东西之外,这一切都是完美无缺的:无论我传递的是什么旗帜,这些物品都是三态的。因此,必须单击该项目两次以选中/取消选中它们。我该怎么做才能使它们成为正常的双态?
创建小部件:
def _locationDetails(self):
self.locationDetails = QListWidget()
self.locationDetails.setFixedHeight(50)
return self.locationDetails
结束项目添加如下:
def addLocationDetail(self, text, checked = True):
item = QListWidgetItem(text)
item.setFlags(QtCore.Qt.ItemIsUserCheckable |
QtCore.Qt.ItemIsSelectable |
QtCore.Qt.ItemIsEnabled)
item.setCheckState(checked)
self.locationDetails.addItem(item)
我调用添加新项目的代码为:
# resolve location:
waypoint.getLocationDetails()
self.locationDetails.clear()
self.addLocationDetail("location=%s" % waypoint.location)
self.addLocationDetail("department=%s" % waypoint.department)
self.addLocationDetail("country=%s" % waypoint.country)
答案 0 :(得分:1)
问题的原因是setCheckState()
函数需要Qt::CheckState
枚举中的值:
枚举Qt :: CheckState
此枚举描述了可检查项目,控件和小部件的状态。
常量值描述
Qt::Unchecked
0项目未选中。
Qt::PartiallyChecked
1部分检查该项目。如果检查了他们的孩子中的一些但不是全部,则可以部分检查分层模型中的项目。
Qt::Checked
2检查项目。
由于默认情况下您传递的值为True
,因此会将其转换为与1
对应的Qt::PartiallyChecked
。
一种可能的解决方案是将布尔值用于Qt::CheckState
类型的适当值:
def addLocationDetail(self, text, checked=True):
item = QListWidgetItem(text)
item.setFlags(QtCore.Qt.ItemIsUserCheckable |
QtCore.Qt.ItemIsSelectable |
QtCore.Qt.ItemIsEnabled)
item.setCheckState(QtCore.Qt.Checked if checked else QtCore.Qt.Unchecked)
self.locationDetails.addItem(item)