PDA

View Full Version : Qt4.1.1: Sorting QCombobox entries



Byngl
15th March 2006, 17:01
With Qt3, you could use combo->listbox()->sort()

Is there a simple way to do this using Qt4 now that the standard listbox is provided by a QListView instead of a QListBox?

jpn
15th March 2006, 18:21
Mmmh.. interesting! :)

It seems that a combo with a "model" sorts itself fine, but a combo with "items" does not.



#include <QtGui>

int main(int argc, char *argv[])
{
QApplication a(argc, argv);

QStringList items;
for (int i = 9; i >= 0; --i)
items << QString::number(i);

QComboBox modelCombo;
modelCombo.setWindowTitle("Model");
modelCombo.setModel(new QStringListModel(items));
modelCombo.model()->sort(0);
modelCombo.show();

QComboBox itemCombo;
itemCombo.setWindowTitle("Item");
itemCombo.addItems(items);
itemCombo.model()->sort(0);
itemCombo.show();

a.connect(&a, SIGNAL(lastWindowClosed()), &a, SLOT(quit()));
return a.exec();
}

jpn
15th March 2006, 18:27
Btw, the only entry (related even a bit to this) I found in the task tracker (http://www.trolltech.com/developer/tasktracker.html?method=entry&id=96748).

Byngl
16th March 2006, 00:32
OK, I can force the model to be a QStringListModel so I can sort it, but if I do, I seem to be losing the ability to assign data to the entries.



//
QComboBox itemCombo;
itemCombo.setWindowTitle("Item");
for (int i = 9; i >= 0; --i)
{
itemCombo.addItem(QString::number(i), 100 + i);
}
for (int i = 0; i < itemCombo.count(); ++i)
{
cout << i << ' ' << itemCombo.itemText(i).toLatin1().data() << ' ';
cout << itemCombo.itemData(i).toInt();
cout << " [" << itemCombo.itemData(i).toString().toLatin1().data() << ']';
cout << endl;
}

//
// Clear the contents and try again, this time with
// a non-default model
//
itemCombo.clear();
itemCombo.setModel(new QStringListModel());
for (int i = 9; i >= 0; --i)
{
itemCombo.addItem(QString::number(i), 100 + i);
}
cout << "==============" << endl;
for (int i = 0; i < itemCombo.count(); ++i)
{
cout << i << ' ' << itemCombo.itemText(i).toLatin1().data() << ' ';
cout << itemCombo.itemData(i).toInt();
cout << " [" << itemCombo.itemData(i).toString().toLatin1().data() << ']';
cout << endl;
}

itemCombo.model()->sort(0);
itemCombo.show();

This produces the following output:

0 9 109 [109]
1 8 108 [108]
2 7 107 [107]
3 6 106 [106]
4 5 105 [105]
5 4 104 [104]
6 3 103 [103]
7 2 102 [102]
8 1 101 [101]
9 0 100 [100]
==============
0 9 0 []
1 8 0 []
2 7 0 []
3 6 0 []
4 5 0 []
5 4 0 []
6 3 0 []
7 2 0 []
8 1 0 []
9 0 0 []
I just checked in qstringlistmodel.cpp and it only returns data for Qt::DisplayRole and Qt::EditRole, not Qt::UserRole. Guess I get to write my own extension...

jpn
17th March 2006, 10:02
I guess an easy solution could be to inherit QStandardItemModel (which QComboBox internally uses) and implement the sorting functionality..