How to use QStyle::standardIcon/standardPixmap with QStyle::StandardPixmap?

Viewed 3068

In my code there is a bunch of calls which try to create QIcons from QStyle standard pixmaps, like:

QIcon groupIcon;
groupIcon.addPixmap( style()->standardPixmap( QStyle::SP_DirClosedIcon ),
                     QIcon::Normal, QIcon::Off );
groupIcon.addPixmap( style()->standardPixmap( QStyle::SP_DirOpenIcon ),
                     QIcon::Normal, QIcon::On );

While this works correctly, in that using the icon for a model's Qt::DecorationRole shows either an open or closed icon based on the item's expanded state, it has two issues:

  1. It's not hi-dpi friendly, and the icons are tiny
  2. QStyle::standardPixmap is marked as obsolete, with QStyle::standardIcon being described as the preferred approach.

I'm unsure how to translate the above code to QStyle::standardIcon though.

QIcon groupIcon( style()->standardIcon( QStyle::SP_DirClosedIcon ) );

works nicely for closed items, and looks great on hidpi. But I can't see how I would add the SP_DirOpenIcon state. There's no equivalent method like "QIcon::addIcon" like there is QIcon::addPixmap.

What's the correct approach to take here, which is hi-dpi friendly and future proof?

1 Answers

how to translate the above code to QStyle::standardIcon

To be able to use QStyle::standardIcon instead of QStyle::standardPixmap, select the particular pixmap from the icon with QIcon::pixmap.

Here is an example I have prepared for you of how to change your code in order to accomplish that:

QIcon groupIcon;
QSize sz(16, 16);

groupIcon.addPixmap(style()->standardIcon(QStyle::SP_DirClosedIcon).pixmap(sz),
                     QIcon::Normal, QIcon::Off);
groupIcon.addPixmap(style()->standardIcon(QStyle::SP_DirOpenIcon).pixmap(sz),
                     QIcon::Normal, QIcon::On);

Here 16 is the requested size. Please note, that:

The pixmap might be smaller than requested, but never larger.

hence adjust this value accordingly.

Related