Need to store and retrieve Qt::UserRole data in a QAbstractTableModel

  • Hi, i have a tableview with a column that use combobox
    I correct subclase QAbstractTableModel and QStyledItemDelegate based on this wiki

    My combobox have many items, so in the ComboBoxItemDelegate::setEditorData i does not want to findText on combobox

    QString currentText =;
    int cbIndex = cb->findText(currentText);

    Just i want to retrieve the index from the model using Qt::UserRole

    int cbIndex =;

    Then in the TableModel try to set Qt::UserRole

    QVariant TmLayers::data(const QModelIndex &index, int role) const
    	if (role == Qt::DisplayRole  && index.column()==1)
    	  { //This work
    	   return QVariant((*mSource)[index.row()].getLayer()->ZScaleName());
       if (role == Qt::UserRole  && index.column()==1)
    	  { //This don´t work
    	   qDebug()<<"UserRole and column 1";
    	   return QVariant((*mSource)[index.row()].getLayer()->ZScaleIndex());
       return QVariant();

    But the model never call the data with role == Qt::UserRole

    What can be wrong?

  • Lifetime Qt Champion


    If you are seeing data properly then it means that you are not using your TmLayers model because currently it would return nothing unless role is Qt::DisplayRole and the column is 1.

  • Thank for the reply but i don´t understand your answer.
    Now the model work perfect.
    In the QVariant TmLayers::data(...) have many if() for the other columns.
    The column with combobox is the number 1

    if ((role == Qt::DisplayRole ||role == Qt::EditRole) && index.column()==1)
    return QVariant((*mSource)[index.row()].getLayer()->ZScaleName());

    It work ok, but inside the itemdelegate I must to search by string:

    void idZScale::setEditorData(QWidget *editor,const QModelIndex &index) const
    QString modelvalue = index.model()->data(index, Qt::EditRole).toString();
    QComboBox comboBox = static_cast<QComboBox>(editor);
    //Recive string then must to find it
    int pos = comboBox->findText(modelvalue,( Qt::MatchExactly | Qt::MatchCaseSensitive ));
    if (pos==-1){qDebug()<<"Don found";comboBox->setCurrentIndex(0);}

    And i want to do that:

    int cbIndex =;

    But i does not know how to store the index value in the model.
    I hope to be clear

  • Lifetime Qt Champion

    You would need to add that to your object but what's the problem with the findText method ? It allows you to reorder the items in the combo box at will without having to worry about that index.

Log in to reply

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