【问题标题】:Can I store some user data in every item of a QListWidget?我可以在 QListWidget 的每个项目中存储一些用户数据吗?
【发布时间】:2011-08-21 06:39:46
【问题描述】:

我想在 QListWidget 中存储一些文件名。我需要完整的文件路径,但我只想显示基本文件名。我可能可以将完整的文件名存储在每个项目的工具提示中,但我宁愿没有列表项目的工具提示。

【问题讨论】:

    标签: c++ qt qlistwidget


    【解决方案1】:

    您可以为每个 QListWidgetItem 设置数据并从中获取数据。请参阅 QListWidgetItem::setData()QListWidgetItem::data()。可以为不同的roles设置数据。使用 Qt::UserRole,它是“第一个可用于特定应用目的的角色”。

    试试这样的:

    QListWidgetItem *newItem = new QListWidgetItem;
    QString fullFilePath("/home/username/file");
    QVariant fullFilePathData(fullFilePath);
    newItem->setData(Qt::UserRole, fullFilePathData);
    newItem->setText(itemText);
    listWidget->insertItem(row, newItem);
    

    和:

    QListWidgeItem* currentItem = listWidget->currentItem();
    if (currentItem != 0) {
         QVariant data = currentItem->data(Qt::UserRole);
         QString fullFilePath = data.toString();
    }
    

    【讨论】:

      【解决方案2】:

      这是它在 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)            
      

      检索数据:

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

      【讨论】:

      • 谢谢 :) 一般问题是当您将数据设置为没有 QtCore.Qt.UserRole 的项目时,它也会更改文本。
      猜你喜欢
      • 2017-09-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-04
      • 2021-11-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多