[英]Getting all data from ListWidgetItem PyQt4
Please have a look at the picture. 请看一下图片。 The bottom widget is a list widget. 底部小部件是列表小部件。 It works like this. 它是这样的。 When you click on insert button a new QListWidgetItem will be added dynamically in the bottom ListWidget. 当您单击插入按钮时,新的QListWidgetItem将动态添加到底部的ListWidget中。 Now there are three items in the widget. 现在,小部件中有三个项目。 Each item may contain CheckBoxes, ComboBoxes, lineEdit etc.. 每个项目可能包含CheckBoxes,ComboBoxes,lineEdit等。
I need to get all those data from the listWidgetItem. 我需要从listWidgetItem中获取所有这些数据。 Unfortunately, the listwidgetitem.text()
is the only way I can retrieve data from the item. 不幸的是, listwidgetitem.text()
是我可以从项目中检索数据的唯一方法。 What to do then, to get all these data. 接下来该怎么做,以获取所有这些数据。
You shouldn't (in general) use QListItemWidget for this, but instead a proper QAbstractItemModel-subclass. 通常,您不应该使用QListItemWidget,而应该使用适当的QAbstractItemModel子类。 With that, you can back your listwidget with whatever data you want, and access that data. 这样,您可以使用所需的任何数据来备份listwidget,并访问该数据。
There is a utility-class available already called QStandardItemModel which inherits from QAbstractItemModel, and should get you started fast. 已经有一个实用程序类称为QStandardItemModel,它从QAbstractItemModel继承而来,可以帮助您快速入门。
Custom QStandardItemModel with custom data method 使用自定义数据方法的自定义QStandardItemModel
You can store multiple pieces of arbitrary data on a QListWidgetItem
(indeed, all the Item widgets support this). 您可以在QListWidgetItem
上存储多条任意数据(实际上,所有Item小部件都支持此功能)。 You need to define a custom role for your data. 您需要为数据定义自定义角色。
Data1Role = QtCore.Qt.UserRole + 1
Data2Role = QtCore.Qt.UserRole + 2
item = QtGui.QListWidgetItem()
item.setData(Data1Role, 'Any data')
item.setData(Data2Role, 42)
print item.data(Data1Role)
# "Any data"
However, this data isn't going to be displayed anywhere on the QListWidgetItem
. 但是,该数据将不会显示在QListWidgetItem
上的任何位置。 The only data that is displayed by default is the data set on the QtCore.Qt.DisplayRole
(which is what text()
and setText()
use). 默认情况下,唯一显示的数据是QtCore.Qt.DisplayRole
上设置的数据(这是text()
和setText()
使用的数据)。
You are probably better off using a QTreeWidget
, which supports multiple columns (for the multiple pieces of data) and creating a custom subclass of QTreeWidgetItem
. 您可能最好使用QTreeWidget
,它支持多列(用于多个数据)并创建QTreeWidgetItem
的自定义子类。 If you want the user to be able to edit the data in the table, you're going to need to create a QItemDelegate
as well to create the QLineEdits
and QComboBoxes
for editing the data. 如果希望用户能够编辑表中的数据,则还需要创建一个QItemDelegate
来创建用于编辑数据的QLineEdits
和QComboBoxes
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.