Can I store some user data in every item of a QListWidget?

后端 未结 2 1970
渐次进展
渐次进展 2021-02-13 01:44

I want to store some filenames in a QListWidget. I need to have the full file paths, but I only want to show the base filename. I probably could store the full filename in the t

2条回答
  •  名媛妹妹
    2021-02-13 01:58

    Here is how it looks like in Python (PyQt5):

    from PyQt5 import QtCore, QtWidgets
    
    
    # Creates a QListWidgetItem
    item_to_add = QtWidgets.QListWidgetItem()
    
    # Setting your QListWidgetItem Text          
    item_to_add.setText('String to Display')   
      
    # Setting your QListWidgetItem Data  
    item_to_add.setData(QtCore.Qt.UserRole, YOUR_DATA) 
    
    # Add the new rule to the QListWidget
    YOUR_QListWidget.addItem(item_to_add)            
    

    Retrieving the data:

    # Looping through items
    for item_index in range(YOUR_QListWidget.count()):  
    
        # Getting the data embedded in each item from the listWidget
        item_data = YOUR_QListWidget.item(item_index).data(QtCore.Qt.UserRole)  
    
        # Getting the datatext of each item from the listWidget
        item_text = YOUR_QListWidget.item(item_index).text()  
    

提交回复
热议问题