PDA

View Full Version : Creating a style for a button



Luc4
23rd April 2010, 10:42
Hi! I would like to create a button whose icon is changed according to its state, i.e. an icon is set if it is not focused and another when it has the focus. I wrote this in the drawControl method of a style I wrote:


switch (element) {
case QStyle::CE_PushButtonBevel: {
// I have to draw the label.
const QStyleOptionButton *buttonOpt = qstyleoption_cast<const QStyleOptionButton *>(option);
QPushButton* buttonWidget = (QPushButton*)widget;

// Draw the correct icon.
qDebug(QString::number(buttonOpt->state, 16).toStdString().c_str());
if ((buttonOpt->state & QStyle::State_HasFocus) == QStyle::State_HasFocus)
// Draw the default pixmap.
painter->drawPixmap(buttonOpt->rect, buttonOpt->icon.pixmap(buttonWidget->size(), QIcon::Selected));
else
// Draw the pixmap to be used in case the widget is focused.
painter->drawPixmap(buttonOpt->rect, buttonOpt->icon.pixmap(buttonWidget->size(), QIcon::Normal));
break;
}
default:
QWindowsStyle::drawControl(element, option, painter, widget);
break;
}

It seems it doesn't work and I'm quite far. I get two icons inside the button. Any idea how I can achieve what I need?
Thanks!

wysota
23rd April 2010, 11:18
You probably don't need to customize the button class at all. Look at what QIcon offers - it allows you to set different pixmaps for different states.

Luc4
23rd April 2010, 14:16
Oh, now I see. I tried this before but I didn't understand it is necessary to set the state to QIcon::On. By default it is set to QIcon::Off. Very useful then! Thanks!