This code example solves how to group multiple CheckBoxes and have only one checkbox be selected in the group, similar to how a group of radial buttons typically function. I think something like this would be a common feature, but I couldn’t find it in the engine.
- A minor change required in CheckBox.h - add:
void InternalSetChecked(bool _bChecked)
{
checked_ = _bChecked;
}
- Add UIEvent
EVENT(E_GROUPCHECKBOX, GroupCheckBoxNamespace)
{
PARAM(P_ELEMENT, Element); // UIElement pointer
}
- GroupCheckBox class
class GroupCheckBox : public UIElement
{
OBJECT(GroupCheckBox);
public:
GroupCheckBox(Context *_pContext)
: UIElement( _pContext )
{
m_vpCheckBox.Clear();
}
~GroupCheckBox()
{
m_vpCheckBox.Clear();
}
void AddCheckBox(CheckBox *_pCheckBox, bool _bChecked)
{
if ( _pCheckBox )
{
_pCheckBox->InternalSetChecked( _bChecked );
AddChild( _pCheckBox );
m_vpCheckBox.Push( _pCheckBox );
SubscribeToEvent( _pCheckBox, E_TOGGLED, HANDLER(GroupCheckBox, HandleCheckBoxToggle));
}
}
CheckBox* GetCheckBox(unsigned _idx)
{
if ( _idx < m_vpCheckBox.Size() )
{
return m_vpCheckBox[ _idx ];
}
return NULL;
}
void HandleCheckBoxToggle(StringHash _eventType, VariantMap& _eventData)
{
using namespace Toggled;
CheckBox *pCheckBox = (CheckBox*)_eventData[P_ELEMENT].GetVoidPtr();
if ( pCheckBox )
{
for ( unsigned i = 0; i < m_vpCheckBox.Size(); ++i )
{
m_vpCheckBox[ i ]->InternalSetChecked( m_vpCheckBox[ i ] == pCheckBox );
}
VariantMap& eventData = GetEventDataMap();
eventData[P_ELEMENT] = this;
SendEvent( E_GROUPCHECKBOX, eventData );
}
}
protected:
Vector<CheckBox*> m_vpCheckBox;
};