问题
I'm trying to read in an xml file and populate a QListWidget
with some of its contents. Each entry should have a checkbox.
In Qt Designer I created the list and added an item that has a checkbox by adding the item to the listWidget, then right clicking on it and selecting Edit Items > Properties > Set Flags to UserCheckable. So i can do it manually.
But when I read in the xml file to populate the ListWidget I can't make these items checkable.
import xml.etree.ElementTree as et
xml_file = os.path.join(path, testcase_file)
tree = et.parse(xml_file)
root = tree.getroot()
for testcases in root.iter('testcase'):
testcase_name = str(testcases.attrib)
item = self.listWidgetTestCases
item.addItem(QtGui.QApplication.translate("qadashboard", testcase_name, None))
# item.setFlags(item.flags() | QtCore.Qt.ItemIsUserCheckable)
# item.setCheckState(QtCore.Qt.Unchecked)
This creates a list of test case name in the list-widget. However I can't make these items into checkboxes. item.setFlags
or ItemIsUserCheckable
is not recognised for list Widgets, so the two lines are commented out in the above example.
回答1:
You're almost there: it's just that you're trying to make the list-widget checkable, rather than each list-widget-item.
Try this instead:
from PyQt5 import QtWidgets, QtCore
self.listWidgetTestCases = QtWidgets.QListWidget()
for testcases in root.iter('testcase'):
testcase_name = str(testcases.attrib)
item = QtWidgets.QListWidgetItem(testcase_name)
item.setFlags(item.flags() | QtCore.Qt.ItemIsUserCheckable)
item.setCheckState(QtCore.Qt.Unchecked)
self.listWidgetTestCases.addItem(item)
(NB: for PyQt4, use QtGui instead of QtWidgets)
来源:https://stackoverflow.com/questions/29149138/how-to-create-a-list-of-checkboxes