Add same item into two separate QListWidgets

时间:2017-04-24 17:31:41

标签: python python-3.x pyqt pyqt5

My project involves two separate QListWidgets with the exact same items. My code successfully adds items to the first list but not the second. Someone must have done this before but search results are for removing duplicate items.

Is it possible to add one item into two QListWidgets without creating new items every time? I could work around this but it seems like an opportunity to learn something.

for item in listItems:
    itm = QtWidgets.QListWidgetItem(item);
    self.lstOne.addItem(itm);
    self.lstTwo.addItem(itm);         #fills the first but not the second

Here is all the code:

# -*- 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_())

1 个答案:

答案 0 :(得分:2)

共享相同项目的两个列表是使用共享模型的QListView个对象的一个​​很好的用例。对于小型列表,您可以使用QStandardItemModel,其中包含QStandardItems,如下所示:

# -*- coding: utf-8 -*-

import sys
from PyQt5 import QtWidgets, QtGui
from PyQt5.QtWidgets import (QWidget, QApplication,  QListView)

class Example(QWidget):

    def __init__(self):
        super().__init__()
        self.initUI()


    def initUI(self):

        self.lstOne = QListView(self)
        self.lstTwo = QListView(self)
        self.lstTwo.move(0,  250)

        model = QtGui.QStandardItemModel(parent=self)

        listItems = ["one",  "two",  "three",  "four"]     

        for item in listItems:
            itm = QtGui.QStandardItem(item)
            model.appendRow(itm)

        self.lstOne.setModel(model)
        self.lstTwo.setModel(model)

        self.setGeometry(300, 300, 500, 500)
        self.show()


if __name__ == '__main__':

    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

如果你有一个大型列表,你应该考虑实现自己的模型类(从QAbstractListModel派生)。这样做的好处是您不需要预先为所有列表元素创建项类,从而提供更好的性能。

您可以阅读有关Qt的模型 - 视图编程here

的更多信息