PDA

View Full Version : Using radio button for checkable QGroupBox



bdp32
5th August 2009, 10:00
Hello, does anyone know a quick way to have the indicator subcontrol of a QGroupBox appear as a radio button instead of a checkbox?

I would like the solution to work for all styles (e.g. using a stylesheet to provide a radio button image would not work as I would have to provide a different image depending on whether the application was using windows style, mac style etc.)

I assume that I'm going to have to reimplement the paint event for the subcontrol, but was wondering if there is a simpler way?

Thanks :)

bdp32
6th August 2009, 12:14
It turns out that subclassing QGroupBox and re-implementing the paint event was easier than I thought. I didn't realise all the QStylePainter/QStyleOption stuff existed until now.

I basically drew the group box, erased the checkbox, then drew a radio button. Does anyone have any comments as to why this might give me problems. (I'm wondering about the way I've erased the checkbox, possibly giving strange artifacts on some fancy style I don't know about).

Re-implemented paintEvent():


void TRadioGroupBox::paintEvent( QPaintEvent * )
{
QStylePainter paint( this );
QStyleOptionGroupBox option;
initStyleOption( &option );
// don't remove the original check box control, as we want to keep
// it as a placeholder
// option.subControls &= ~QStyle::SC_GroupBoxCheckBox;
paint.drawComplexControl( QStyle::CC_GroupBox, option );

// re-use the style option, it contians enough info to make sure the
// button is correctly checked
option.rect = style()->subControlRect( QStyle::CC_GroupBox, &option,
QStyle::SC_GroupBoxCheckBox, this );

// now erase the checkbox
paint.save();
QPixmap px( option.rect.width(), option.rect.height() );
px.fill( this, option.rect.left(), option.rect.top() );
QBrush brush( px );
paint.fillRect( option.rect, brush );
paint.restore();

// and replace it with a radio button
paint.drawPrimitive( QStyle::PE_IndicatorRadioButton, option );
}