Qt - Get QPushButton icon name

2019-07-27 09:02发布

问题:

I have a two state QPushButton. I want to associate an icon to each state.

It is like Play|Pause buttons in music players.

To do so, I would like to get the current icon name in order to know what the next icon to set will be.

I could subclass QPushButton but is it worth it?

回答1:

Use QPushButton::icon() and QIcon::name() to get the icon name.



回答2:

Instead of setting an icon based on the QPushButton's state, set one QIcon that has two states, Qt will select the correct icon if you use it with a checkable QPushButton.

QIcon icon = QIcon();
// 'Off' state corresponds to unchecked state of QPushButton
icon.addPixmap( QPixmap( ":/img/play.png" ), QIcon::Normal, QIcon::Off );
// 'On' state corresponds to checked state of QPushButton
icon.addPixmap( QPixmap( ":/img/pause.png" ), QIcon::Normal, QIcon::On );
QPushButton * button = new QPushButton();
button->setIcon( icon );
button->setCheckable( true );