I am trying to understand how data roles are used by QComboBox class. I want to add items that are displayed in one way, but edited in another way, e.g. item is displayed as "Item 1", but when I select it, it should be placed to the edit field as "1". I tried to use Qt:
isplayRole and Qt::EditRole, but I noticed something strange: it seems like values are displayed for the role I used for the last time. In following example items are shown for the EditRole, even if I set combobox as not editable, but it worth to swap those two lines and DisplayRole will be used everywhere, even in the edit field. Could somebody explain me thing behavior?
#include <QtCore>
#include <QApplication>
#include <QtGui>
int main(int argc, char *argv[])
{
comboBox.setEditable(true);
for (int i = 0; i<3; ++i)
{
comboBox.
addItem(QString("item %1").
arg(i
));
comboBox.
setItemData(i,
QString("display %1").
arg(i
), Qt
::DisplayRole);
comboBox.setItemData(i, i, Qt::EditRole);
}
comboBox.show();
return a.exec();
}
#include <QtCore>
#include <QApplication>
#include <QtGui>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QComboBox comboBox;
comboBox.setEditable(true);
for (int i = 0; i<3; ++i)
{
comboBox.addItem(QString("item %1").arg(i));
comboBox.setItemData(i, QString("display %1").arg(i), Qt::DisplayRole);
comboBox.setItemData(i, i, Qt::EditRole);
}
comboBox.show();
return a.exec();
}
To copy to clipboard, switch view to plain text mode
Bookmarks