Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show standard warning icon in Qt4

I'm trying to display a "warning" icon next to a QLineEdit if it contains invalid data.
I was trying to use QStyle::standardIcon(QStyle::SP_MessageBoxWarning) to get a standard pixmap and place it inside a QLabel, and in some cases this seems to work. When running Gnome the icon is displayed correctly, but when running under KDE no icon is shown. I assume that the warning icon is simply not included in the style used under KDE.

What is the preferred way to display a "standard" warning icon in Qt? Does there exist some list which shows which icons are included in every style? How can I get an icon from a style that I know includes the warning icon?

like image 300
pafcu Avatar asked Dec 15 '10 19:12

pafcu


3 Answers

The last time I had a similar problem, I found this Qt labs discussion useful. It informed me that QIcon now (since 4.6 I believe) has a QIcon::fromTheme function that allows you to load an icon based on the Freedesktop.org Icon Naming Specification, and in addition provide a fallback icon to be used if the current theme does not have the icon in question.

What I did was then to include some very basic icons for use as fallback, and in general specify icons only by their Freedesktop names. This gave a theme-consistent look almost always, and the program still worked in cases where people were missing icons.

As for the warning icon, I'm guessing/hoping that every theme must have the one named "dialog-warning", and that it's what you're looking for.

I hope this helps.

Edit: Oh and, in case you don't know, it can be useful to look at for example the Tango icon set to get a rough idea of what the Freedesktop names correspond to (although it is of course theme-dependent).

like image 118
gspr Avatar answered Sep 28 '22 01:09

gspr


Qt does bundle a number of images that are resources that you can use in your own code. These images are a superset of those available via standardIcon() You may want to verify that the particular image is included in the versions of Qt you're targeting.

The end result could look like the following:

QPixmap pixmap(":/trolltech/styles/commonstyle/images/up-128.png");
// use pixmap as needed
like image 35
Kaleb Pederson Avatar answered Sep 28 '22 02:09

Kaleb Pederson


For anyone who wants to know how to do this in a Windows environment you can:

Create a qLabel in your custom class, and then in the constructor of that class create a QIcon with the style you want, convert it into a pixmap and use the QLabel::setPixmap() function to apply it to the one you created:

QIcon icon = style()->standardIcon(QStyle::SP_MessageBoxWarning); //or 
//whatever icon you choose
QPixmap pixmap = icon.pixmap(QSize(60, 60));
ui->iconLabel->setPixmap(pixmap);

ui->iconLabel->setScaledContents(true); //you can set this to fill the 
//dimensions of your qLabel if you wish.
like image 25
Link H. Avatar answered Sep 28 '22 01:09

Link H.