PDA

View Full Version : QTreeView with varying icon size



Thuan Seah Tan
1st February 2012, 22:55
Hi everyone,

I have a question regarding the default behaviour of QTreeView. I have a tree view with various different items like folders and file and each have a different icon of different size. The folder's icon is 28x22 and the file's icon is 18x21. When displaying the view, Qt seems to have attempt to keep the width fixed to 18 and a value close to that and the icon of the folder is shrunk to fit. So far, the only way I found to make QTreeView accommodate for the largest icon is to can setIconSize with the size of the largest icon as the parameter.

Wondering what's the default behaviour of QTreeView when it comes to icon size? Is calling setIconSize my best bet?

Thuan

KillGabio
2nd February 2012, 01:14
I had almost the same problem but in my case was with menuItem icons...your solution is possible. But I was recommended to make something like this:

//header

#ifndef ICONSIZE_H
#define ICONSIZE_H

#include <QObject>
#include <QStyle>
#include <QWindowsStyle>

class IconSize : public QWindowsStyle
{
Q_OBJECT
public:
explicit IconSize(QWindowsStyle *parent = 0);
int pixelMetric(PixelMetric metric, const QStyleOption * option = 0, const QWidget * widget = 0 ) const;

signals:

public slots:

};


//CPP


#include "iconsize.h"

IconSize::IconSize(QWindowsStyle *parent) :
QWindowsStyle()
{
Q_UNUSED (parent);
}

int IconSize::pixelMetric(PixelMetric metric, const QStyleOption * option, const QWidget * widget)const
{
int s = QWindowsStyle::pixelMetric(metric, option, widget);
if (metric == QStyle::PM_SmallIconSize) {
s = 23;
}
return s;
}

I reimplemented the necessary methods (in this case only one) of the Windows Style that is the one I use for my application.

Thuan Seah Tan
2nd February 2012, 03:27
Thanks for the response.

I looked into Qt source code and it seems for some reason if you have a QIcon, it will try to find the best icon that is no larger than the size specified by the decorationSize of the option. If you have a QPixmap, it will actually use the size of the image. Which in my situation, the decorationSize defaults to 16x16 (i.e. small icon) and during the paint, it draws the icon for file which is a QPixmap correctly, but shrinks the QIcon for the folder.

For my case, I ended up calling setIconSize() which seems simpler to me.

MarekR22
2nd February 2012, 08:57
IMHO you should correct data model.
Note that there is a Qt::SizeHintRole.
So subclass data model you are using and override QAbstractItemModel::data (and/or: QAbstractItemModel::itemData)to provide Qt::SizeHintRole value.

It can be also done on view level by overriding QAbstractItemView::sizeHintForRow.

Playing with delegate can also do the trick.