[英]How do I update the data associated with a QListWidgetItem from the QListWidget in PyQt?
I have a QListWidget
that has 10 QListWidgetItems
.我有一个
QListWidget
有 10 个QListWidgetItems
。 When each of those QListWidgetItems
is created I do something like this:创建这些
QListWidgetItems
中的每一个时,我都会执行以下操作:
item = QtGui.QListWidgetItem("Text to Show")
item.setData(36, "A specific value that is used later")
self.ui.my_list.addItem(item)
Now, later in the application, after a user clicks a button, I want to update the text "A specific value that is used later", for the item that is selected.现在,稍后在应用程序中,在用户单击按钮后,我想为所选项目更新文本“稍后使用的特定值”。 I have attempted to do this
我试图这样做
ndx = self.ui.my_list.currentRow()
self.ui.my_list.item(ndx).setData(36, "Updated!")
The problem is, this doesn't work.问题是,这是行不通的。 It doesn't throw any errors, but the data is just gone.
它不会抛出任何错误,但数据就这样消失了。 In my button press signal I have this code to see the value before and after the reassignment:
在我的按钮按下信号中,我有这段代码可以查看重新分配前后的值:
ndx = self.ui.my_list.currentRow()
print "Before:", self.ui.my_list.item(ndx).data(36).toPyObject()
self.ui.my_list.item(ndx).setData(36, "Updated!")
print "After:", self.ui.my_list.item(ndx).data(36).toPyObject()
This outputs:这输出:
Before: A specific value that is used later
After:
How can I properly change the data so that it is saved back to the QListWidgetItem
?如何正确更改数据以便将其保存回
QListWidgetItem
?
You may want to check that the role value your using is a valid user role, otherwise it may be altered internally.您可能需要检查您使用的角色值是否是有效的用户角色,否则它可能会在内部被更改。 I write in c++, but I use the QListWidget and QListWidgetItem(s) frequently, and this was a problem I encountered early on.
我写在c++,但是我经常使用QListWidget和QListWidgetItem(s),这是我早期遇到的问题。 I imagen that the functionality is similar regardless of the language.
我认为无论使用哪种语言,功能都是相似的。 According to the documentation here , the first user role that can be used is 0x0010.
根据此处的文档,可以使用的第一个用户角色是 0x0010。 So to tie it to your example, you might try the following:
因此,为了将其与您的示例联系起来,您可以尝试以下操作:
item.setData(0x0010, "A specific value that is used later") item.setData(0x0010, "后面用到的具体值")
For additional item roles you would use 0x0011, 0x0012, 0x0013, etc.对于其他项目角色,您可以使用 0x0011、0x0012、0x0013 等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.