![](/img/trans.png)
[英]How can I remove a QListWidgetItem from a QListWidget and refresh the display?
[英]How do I update the data associated with a QListWidgetItem from the QListWidget in PyQt?
我有一個QListWidget
有 10 個QListWidgetItems
。 創建這些QListWidgetItems
中的每一個時,我都會執行以下操作:
item = QtGui.QListWidgetItem("Text to Show")
item.setData(36, "A specific value that is used later")
self.ui.my_list.addItem(item)
現在,稍后在應用程序中,在用戶單擊按鈕后,我想為所選項目更新文本“稍后使用的特定值”。 我試圖這樣做
ndx = self.ui.my_list.currentRow()
self.ui.my_list.item(ndx).setData(36, "Updated!")
問題是,這是行不通的。 它不會拋出任何錯誤,但數據就這樣消失了。 在我的按鈕按下信號中,我有這段代碼可以查看重新分配前后的值:
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()
這輸出:
Before: A specific value that is used later
After:
如何正確更改數據以便將其保存回QListWidgetItem
?
您可能需要檢查您使用的角色值是否是有效的用戶角色,否則它可能會在內部被更改。 我寫在c++,但是我經常使用QListWidget和QListWidgetItem(s),這是我早期遇到的問題。 我認為無論使用哪種語言,功能都是相似的。 根據此處的文檔,可以使用的第一個用戶角色是 0x0010。 因此,為了將其與您的示例聯系起來,您可以嘗試以下操作:
item.setData(0x0010, "后面用到的具體值")
對於其他項目角色,您可以使用 0x0011、0x0012、0x0013 等。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.