QListWidgetItem->setData() with different roles fails



  • Assume the following code:
    @
    QDate currentDate = QDate::currentDate();

    QListWidgetItem *item = new QListWidgetItem;
    item->setData(Qt::EditRole, currentDate );
    item->setData(Qt::DisplayRole, date.toString("dd.MM.yyyy"));
    @
    Now, If I try to get the edit role with:
    @QDate date = item->data(Qt::EditRole).value<QDate>()@
    the result is empty (jd=0).

    That is because item->data(Qt::EditRole) returns the display role, in this case a QString.

    Is that a known bug or is there an error in my understandig of roles?

    I'm using Qt 4.8.1

    Regards,
    Harald

    Edit: please use @ tags around code sections; Andre



  • Ok, I found it by looking at QListWidget.cpp::setData():
    Qt::EditRole is casted to Qt::Display role, so the second setData()-call overrides the first one, since it has the same key.

    I will use Qt::UserRole instead of Qt::EditRole



  • Hi there, you mixed it up a bit. The Display role is used by the model to give the current text to be displayed. The EditRole is used by the view to give the model new text to be stored as current text.
    Example (in the model of course):
    @
    bool YourModel::setData(const QModelIndex &index,
    const QVariant &value, int role)
    {
    if (index.isValid() && role == Qt::EditRole) {

         yourList.replace(index.row(), value.toString());
         emit dataChanged(index, index);
         return true;
     }
     return false;
    

    }

    QVariant yourModel::data(const QModelIndex &index, int role) const
    {
    if (!index.isValid())
    return QVariant();

     if (index.row() >= yourList.size())
         return QVariant();
    
     if (role == Qt::DisplayRole)
         return yourList.at(index.row());
     else
         return QVariant();
    

    }
    @
    So in basic when using the Widget version it all happens on the background and the editrole and display role gets handled the same way.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.