When QTreeWidget has sorting set to true, setting item's icon can reorder the item. This shouldn't happen. In below example after pressing "Reload" the items' icons are set and the order of items is changed.
This is because QTreeModel::ensureSorted doesn't do a stable sort
main.cpp:
#include <QApplication>
#include <QPushButton>
#include <QTreeWidget>
#include <QVBoxLayout>
#include <QImage>
#include <QDebug>
class MyTree : public QWidget
{
Q_OBJECT
public:
MyTree(QWidget *parent = 0) : QWidget(parent)
{
QPushButton *b = new QPushButton(tr("Reload"));
m_treeWidget = new QTreeWidget(this);
m_item1 = new QTreeWidgetItem(m_treeWidget);
m_item2 = new QTreeWidgetItem(m_treeWidget);
m_item1->setText(0, tr("Item"));
m_item2->setText(0, tr("Item"));
QVBoxLayout *l = new QVBoxLayout(this);
l->addWidget(b);
l->addWidget(m_treeWidget);
connect(b, SIGNAL(clicked()), this, SLOT(slotReload()));
m_treeWidget->setSortingEnabled(true);
QImage img1(16, 16, QImage::Format_RGB32);
img1.fill(0xFF0000);
QIcon icon1(QPixmap::fromImage(img1));
QImage img2(16, 16, QImage::Format_RGB32);
img2.fill(0x00FF00);
QIcon icon2(QPixmap::fromImage(img2));
m_item1->setData(0, 1234, qVariantFromValue(img1));
m_item2->setData(0, 1234, qVariantFromValue(img2));
}
private slots:
void slotReload()
{
const int oldItem1Pos = m_treeWidget->indexOfTopLevelItem(m_item1);
m_treeWidget->topLevelItem(0)->setIcon(0, QIcon(QPixmap::fromImage(qVariantValue<QImage>(m_treeWidget->topLevelItem(0)->data(0, 1234)))));
m_treeWidget->topLevelItem(1)->setIcon(0, QIcon(QPixmap::fromImage(qVariantValue<QImage>(m_treeWidget->topLevelItem(1)->data(0, 1234)))));
const int newItem1Pos = m_treeWidget->indexOfTopLevelItem(m_item1);
qDebug() << "old Position of item 1:" << oldItem1Pos << ", new pos of item 1:" << newItem1Pos;
}
private:
QTreeWidget *m_treeWidget;
QTreeWidgetItem *m_item1;
QTreeWidgetItem *m_item2;
};
int main(int argc, char **argv)
{
QApplication app(argc, argv);
MyTree tree;
tree.show();
return app.exec();
}
#include "main.moc"