Copying all items from QListWidget to another

Viewed 492

I'm trying to implement copying all items from one Qlistwidget to another in pyqt5 but I can't get the right method of doing it. Any suggestions will be appreciated.

This is the sample code of what I'm trying to implement:

def expand_camera_view(self):
    for i in range(self.cameraList.count()-1):
        new_item = self.cameraList.item(i)
        self.allCamerasList.addItem(new_item)

I want to copy items from cameraList to allCamerasList. Both are QListWidgets. Thank you

1 Answers

You can use the clone() method of the QListWidgetItem:

from PyQt5 import QtWidgets


if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)

    left_lw = QtWidgets.QListWidget()

    for i in range(5):
        it = QtWidgets.QListWidgetItem(f"item-{i}")
        left_lw.addItem(it)

    right_lw = QtWidgets.QListWidget()

    # copy items
    for i in range(left_lw.count()):
        clone_it = left_lw.item(i).clone()
        right_lw.addItem(clone_it)

    w = QtWidgets.QWidget()
    lay = QtWidgets.QVBoxLayout(w)
    lay.addWidget(left_lw)
    lay.addWidget(right_lw)
    w.show()

    sys.exit(app.exec_())
Related