简体   繁体   中英

PySide QtGui.QListWidget: how to associate to object data

I am building a GUI in FreeCAD using the built-in PySide module. Is there a simple/standard way to 'attach' data to a list item in a PySide QtGui.QListWidget? So far, I have this (note this is not the complete code, but hopefully gets the point across):

Class fcGui(QtGui.QWidget):

    def initUI(self):
        self.listWidget = QtGui.QListWidget(self)
        self.objData = []
        self.listWidget.setSelectionMode(QtGui.QAbstractItemView.ExtendedSelection)
        for i in range(0,len(App.ActiveDocument.Objects)):
            self.listWidget.addItem(App.ActiveDocument.Objects[i].Name)

    def acceptance(self):
        print(self.listWidget.selectedItems())

This prints the selected items by name. But now I need to do something with the objects associated with these names. Is there a straightforward way to do this? All I can come up with is a complicated scheme to determine the index of each selected item, and associate that with a list of the corresponding objects. Any help would be appreciated.

You can use a custom role to store the object:

ObjectRole = QtCore.Qt.UserRole + 1000


Class fcGui(QtGui.QWidget):
    def initUI(self):
        self.listWidget = QtGui.QListWidget(self)
        self.objData = []
        self.listWidget.setSelectionMode(QtGui.QAbstractItemView.ExtendedSelection)
        for obj in App.ActiveDocument.Objects:
            it = QtGui.QListWidgetItem(obj.Name)
            it.setData(ObjectRole, obj)
            self.listWidget.addItem(it)

    def acceptance(self):
        for it in self.listWidget.selectedItems():
            obj = it.data(ObjectRole)
            print(obj, obj.Name)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM