0
我的項目涉及兩個完全相同項目的獨立QListWidgets。我的代碼成功地將項目添加到第一個列表,但不是第二個。有人必須先完成此操作,但搜索結果是用於刪除重複的項目。將相同的項目添加到兩個單獨的QListWidgets中
是否可以將一個項目添加到兩個QListWidgets中,而無需每次創建新項目?我可以解決這個問題,但它似乎是一個學習的機會。
for item in listItems:
itm = QtWidgets.QListWidgetItem(item);
self.lstOne.addItem(itm);
self.lstTwo.addItem(itm); #fills the first but not the second
這裏是所有代碼:
# -*- coding: utf-8 -*-
import sys
from PyQt5 import QtWidgets
from PyQt5.QtWidgets import (QWidget, QApplication, QListWidget)
class Example(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.lstOne = QListWidget(self)
self.lstTwo = QListWidget(self)
self.lstTwo.move(0, 250)
listItems = ["one", "two", "three", "four"]
for item in listItems:
itm = QtWidgets.QListWidgetItem(item);
self.lstOne.addItem(itm);
self.lstTwo.addItem(itm); #fills the first but not the second
self.setGeometry(300, 300, 500, 500)
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
在那裏,我知道我會學到一些東西。謝謝!這似乎是一個更好的方法。只是爲了好奇,爲什麼我的物品沒有被添加到兩個列表小部件? – jshort
由於'QListWidgetItem's被設計用於一個'QListWidget'中(你甚至可以從該項目中獲得[reference](http://doc.qt.io/qt-4.8/qlistwidgetitem.html#listWidget)到包含該項目的列表小部件)。試圖在兩個'QListWidgets'中使用它會導致未定義的行爲。順便說一句,如果我的文章回答你的問題,然後請將其標記爲已回答 – titusjan
感謝您滿足我的好奇心和答案的深度。標記爲回答並投票。 – jshort