如何创建复选框列表 [英] How to create a list of checkboxes
问题描述
我正在尝试读取xml文件,并使用其中的某些内容填充 QListWidget
。每个条目应具有一个复选框。
I'm trying to read in an xml file and populate a QListWidget
with some of its contents. Each entry should have a checkbox.
在Qt Designer中,我创建了列表,并添加了一个具有复选框的项目,方法是将该项目添加到listWidget,然后右键单击它并选择编辑项目>属性>将标志设置为UserCheckable。因此,我可以手动完成。
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.
但是当我读取xml文件以填充ListWidget时,我无法使这些项目可检查。
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)
列表小部件中测试用例名称的列表。但是,我无法将这些项目放入复选框。列表小部件无法识别 item.setFlags
或 ItemIsUserCheckable
,因此在上面的示例中注释了两行。
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.
推荐答案
您快到了:只是您要制作列表小工具可检查,而不是每个列表小部件。
You're almost there: it's just that you're trying to make the list-widget checkable, rather than each list-widget-item.
尝试以下操作:
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)
(注意:对于PyQt4,请使用QtGui而不是QtWidgets)
(NB: for PyQt4, use QtGui instead of QtWidgets)
这篇关于如何创建复选框列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!