Search code examples
pythonpython-2.7pyqtpyqt4qlistwidget

QListWidgetItem holding data from list to list


I am trying to set QlistWidgetItem to have an object stored with in. I am using the setData function to achive this. I can get the data to be stored in an item while it is in list A. However I am trying to move the QlistWidgetItem to list B and when doing so it loses the data from when it was in list A. I have tried to read the data out of listA.item and then when creating listB.item store it in there with the same method but have had no success.

http://doc.qt.io/archives/qt-4.8/qlistwidgetitem.html#setData

Please see the code below as it is an example of what I am trying to do. If you run the program below you will see it load a Example item into the bottom list. I then try to move the list to the top and back to the bottom while keeping the data element inside but it is getting lost in the process. Any help would be amazing!

import sys
from PyQt4 import QtGui, QtCore

class Struct():
    def __init__(self,row):
        self.hotkey=row['hotkey']
        self.command=row["COMMAND"]

class Example(QtGui.QWidget):

    def __init__(self):
        super(Example, self).__init__()
        self.setMinimumSize(600, 400)
        self.initUI()

    def initUI(self):      

        self.pushButton = QtGui.QPushButton(self)
        self.pushButton.setGeometry(QtCore.QRect(90, 630, 100, 41))
        self.pushButton.setObjectName(("pushButton"))
        self.listWidget = QtGui.QListWidget(self)
        self.listWidget.setGeometry(QtCore.QRect(20, 90, 261, 220))
        self.listWidget.setObjectName(("listWidget"))
        self.listWidget_2 = QtGui.QListWidget(self)
        self.listWidget_2.setGeometry(QtCore.QRect(20, 379, 261, 211))
        self.listWidget_2.setObjectName(("listWidget_2"))
        self.pushButton_2 = QtGui.QPushButton(self)
        self.pushButton_2.setGeometry(QtCore.QRect(160, 320, 31, 31))
        self.pushButton_2.setObjectName(("pushButton_2"))
        self.pushButton_3 = QtGui.QPushButton(self)
        self.pushButton_3.setGeometry(QtCore.QRect(100, 320, 31, 31))
        self.pushButton_3.setObjectName(("pushButton_3"))
        self.pushButton.clicked.connect(self.testData)
        self.pushButton_2.clicked.connect(self.moveItemsTopToBottom)
        self.pushButton_3.clicked.connect(self.moveItemsBottomToTop)
        self.loadRightList()
        self.loadLeftList()
        self.listWidget_2.setSelectionMode(QtGui.QAbstractItemView.ExtendedSelection)
        self.listWidget.setSelectionMode(QtGui.QAbstractItemView.ExtendedSelection)
        self.show()


    def testData(self, state):
        print self.listWidget_2.item(0).text()
        print self.listWidget_2.item(0).data(32).toPyObject().hotkey
    def moveItemsTopToBottom(self,state): 
        for i in self.listWidget.selectedItems():
            x= i.data(32).toPyObject()
            self.listWidget_2.addItem(i.text())
            self.listWidget.takeItem(self.listWidget.row(i))
            item_num=self.listWidget.count()-1
        return
    def moveItemsBottomToTop(self,state): 
        for i in self.listWidget_2.selectedItems():
            self.listWidget.addItem(i.text())
            self.listWidget_2.takeItem(self.listWidget_2.row(i))
            item_num=self.listWidget_2.count()-1
            self.listWidget_2.item(item_num)
        return
    def loadLeftList(self):

        results = []
        if (results!=[]):
            for i in results:
                self.listWidget.addItem(i['NAME'])
                item_num=self.listWidget.count()-1
                self.listWidget.item(item_num).setToolTip(i['COMMAND'])
                x=Struct(i)
                self.listWidget.item(item_num).setData(32,x)
        return
    def loadRightList(self):

        results= [{'NAME': 'Example Query 1', 'TEAM_CD': 1, 'TYPE_CD': 0, 'COMMAND': 'SELECT * FROM CHARGE C WHERE C.ACTIVE_IND = 1', 'hotkey': 'cinfo', 'COMMAND_ID': 2}]
        if (results!=None):
            for i in results:
                self.listWidget_2.addItem(i['NAME'])
                item_num=self.listWidget_2.count()-1
                self.listWidget_2.item(item_num).setToolTip(i['COMMAND'])
                x=Struct(i)
                self.listWidget_2.item(item_num).setData(32,x)
                print self.listWidget_2.item(item_num).data(32).toPyObject().hotkey
        else:   
            return None


def main():
    app = QtGui.QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()

Solution

  • What I see in your code is that you copy the QListWidgetItem text from one QListWidget to the other, you are not moving the QListWidgetItem. the takeItem() method returns the QListWidgetItem without a parent, so you just have to add it to the other.

    class Example(QtGui.QWidget):
    
        def __init__(self):
            super(Example, self).__init__()
            self.setMinimumSize(600, 400)
            self.initUI()
    
        def initUI(self):      
            lay = QtGui.QVBoxLayout(self)
            self.topListWidget = QtGui.QListWidget(self)
            self.bottomListWidget = QtGui.QListWidget(self)
            toTopButton = QtGui.QPushButton("to top", self)
            toBottomButton = QtGui.QPushButton("to bottom", self)
            printButton = QtGui.QPushButton("print", self)
            hlay = QtGui.QHBoxLayout()
            hlay.addWidget(toBottomButton)
            hlay.addWidget(toTopButton)
            lay.addWidget(self.topListWidget)
            lay.addLayout(hlay)
            lay.addWidget(self.bottomListWidget)
            lay.addWidget(printButton)
    
            self.topListWidget.setSelectionMode(QtGui.QAbstractItemView.ExtendedSelection)
            self.bottomListWidget.setSelectionMode(QtGui.QAbstractItemView.ExtendedSelection)
    
            self.show()
            printButton.clicked.connect(self.testData)
            self.loadRightList()
            toBottomButton.clicked.connect(self.moveItemsTopToBottom)
            toTopButton.clicked.connect(self.moveItemsBottomToTop)
    
    
        def testData(self, state):
            for i in range(self.topListWidget.count()):
                it = self.topListWidget.item(i)
                print("top: ", it.data(QtCore.Qt.UserRole).toPyObject().hotkey)
    
            for i in range(self.bottomListWidget.count()):
                it = self.bottomListWidget.item(i)
                print("bottom: ", it.data(QtCore.Qt.UserRole).toPyObject().hotkey)
    
    
        def moveItemsTopToBottom(self,state): 
            for item in self.topListWidget.selectedItems():
                it = self.topListWidget.takeItem(self.topListWidget.row(item))
                self.bottomListWidget.addItem(it)
    
        def moveItemsBottomToTop(self,state): 
            for item in self.bottomListWidget.selectedItems():
                it = self.bottomListWidget.takeItem(self.bottomListWidget.row(item))
                self.topListWidget.addItem(it)
    
        def loadRightList(self):
            results= [{'NAME': 'Example Query 1', 'TEAM_CD': 1, 'TYPE_CD': 0, 'COMMAND': 'SELECT * FROM CHARGE C WHERE C.ACTIVE_IND = 1', 'hotkey': 'cinfo', 'COMMAND_ID': 2}]
            for result in results:
                item = QtGui.QListWidgetItem(result["NAME"])
                item.setToolTip(result["COMMAND"])
                item.setData(QtCore.Qt.UserRole, Struct(result))
                self.topListWidget.addItem(item)