如何使 QListWidgetItem 不是三态?

how to make QListWidgetItem NOT tristate?

我有一个带有 QListWidget 的表单,我在其中反复添加新项目。这一切都完美无缺,除了一件事:无论我通过什么标志,这些项目都是三态的。因此,必须单击该项目两次才能 check/uncheck 它们。我应该怎么做才能让他们正常双态?

小部件是这样创建的:

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)

问题是因为setCheckState() function needs a value from the Qt::CheckState枚举:

enum Qt::CheckState

This enum describes the state of checkable items, controls, and widgets.

Constant Value Description

Qt::Unchecked 0 The item is unchecked.

Qt::PartiallyChecked 1 The item is partially checked. Items in hierarchical models may be partially checked if some, but not all, of their children are checked.

Qt::Checked 2 The item is checked.

并且由于您默认向其传递 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)