wxPropertyGrid is a specialized grid for editing properties - in other words name = value pairs.
List of ready-to-use property classes include strings, numbers, flag sets, fonts, colours and many others. It is possible, for example, to categorize properties, set up a complete tree-hierarchy, add more than two columns, and set arbitrary per-property attributes.
As this version of wxPropertyGrid has some backward-incompatible changes from version 1.4, everybody who need to maintain custom property classes should carefully read final section in Changes from wxPropertyGrid 1.4.
As seen here, wxPropertyGrid is constructed in the same way as other wxWidgets controls:
(for complete list of new window styles, see wxPropertyGrid Window Styles)
wxPropertyGrid is usually populated with lines like this:
Naturally, wxStringProperty is a property class. Only the first function argument (label) is mandatory. Second one, name, defaults to label and, third, the initial value, to default value. If constant wxPG_LABEL is used as the name argument, then the label is automatically used as a name as well (this is more efficient than manually defining both as the same). Use of empty name is discouraged and will sometimes result in run-time error. Note that all property class constructors have quite similar constructor argument list.
To demonstrate other common property classes, here's another code snippet:
Operations on properties are usually done by directly calling wxPGProperty's or wxPropertyGridInterface's member functions. wxPropertyGridInterface is an abstract base class for property containers such as wxPropertyGrid, wxPropertyGridManager, and wxPropertyGridPage. Note however that wxPGProperty's member functions generally do not refresh the grid.
wxPropertyGridInterface's property operation member functions , such as SetPropertyValue() and DisableProperty(), all accept a special wxPGPropArg id argument, using which you can refer to properties either by their pointer (for performance) or by their name (for convenience). For instance:
Using pointer is faster, since it doesn't require hash map lookup. Anyway, you can always get property pointer (wxPGProperty*) as return value from Append() or Insert(), or by calling wxPropertyGridInterface::GetPropertyByName() or just plain GetProperty().
wxPropertyGrid has a hierarchic property storage and display model, which allows property categories to hold child properties and even other categories. Other than that, from the programmer's point of view, categories can be treated exactly the same as "other" properties. For example, despite its name, GetPropertyByName() also returns a category by name. Note however that sometimes the label of a property category may be referred as caption (for example, there is wxPropertyGrid::SetCaptionTextColour() method that sets text colour of property category labels).
When category is added at the top (i.e. root) level of the hierarchy, it becomes a current category. This means that all other (non-category) properties after it are automatically appended to it. You may add properties to specific categories by using wxPropertyGridInterface::Insert or wxPropertyGridInterface::AppendIn.
Category code sample:
Basically any property can have children. There are few limitations, however.
wxEnumProperty is used when you want property's (integer or string) value to be selected from a popup list of choices.
Creating wxEnumProperty is slightly more complex than those described earlier. You have to provide list of constant labels, and optionally relevant values (if label indexes are not sufficient).
A very simple example:
Here's extended example using values as well:
wxPGChoices is a class where wxEnumProperty, and other properties which require storage for list of items, actually stores strings and values. It is used to facilitate reference counting, and therefore recommended way of adding items when multiple properties share the same set.
You can use wxPGChoices directly as well, filling it and then passing it to the constructor. In fact, if you wish to display bitmaps next to labels, your best choice is to use this approach.
wxEditEnumProperty works exactly like wxEnumProperty, except is uses non-read-only combo box as default editor, and value is stored as string when it is not any of the choices.
wxFlagsProperty has similar construction:
wxFlagsProperty can use wxPGChoices just the same way as wxEnumProperty Note: When changing "choices" (ie. flag labels) of wxFlagsProperty, you will need to use wxPGProperty::SetChoices() to replace all choices at once - otherwise implicit child properties will not get updated properly.
This section describes the use of less often needed property classes. To use them, you have to include <wx/propgrid/advprops.h>.
Properties store their values internally as wxVariant, but is also possible to obtain them as wxAny, using implicit conversion. You can get property values with wxPGProperty::GetValue() and wxPropertyGridInterface::GetPropertyValue().
Below is a code example which handles wxEVT_PG_CHANGED event:
You can get a string-representation of property's value using wxPGProperty::GetValueAsString() or wxPropertyGridInterface::GetPropertyValueAsString(). This particular function is very safe to use with any kind of property.
Note that in some cases property value can be Null variant, which means that property value is unspecified. This usually occurs only when wxPG_EX_AUTO_UNSPECIFIED_VALUES extra window style is defined or when you manually set property value to Null (or unspecified).
You can use somewhat STL'ish iterator classes to iterate through the grid. Here is a simple example of forward iterating through all individual properties (not categories nor private child properties that are normally 'transparent' to application code):
As expected there is also a const iterator:
You can give some arguments to GetIterator to determine which properties get automatically filtered out. For complete list of options, see wxPropertyGridIterator Flags. GetIterator() also accepts other arguments. See wxPropertyGridInterface::GetIterator() for details.
This example reverse-iterates through all visible items:
GetIterator() only works with wxPropertyGrid and the individual pages of wxPropertyGridManager. In order to iterate through an arbitrary property container (such as entire wxPropertyGridManager), you need to use wxPropertyGridInterface::GetVIterator(). Note however that this virtual iterator is limited to forward iteration.
Example of populating an empty wxPropertyGrid from a values stored in an arbitrary list of wxVariants.
Class wxPropertyGridPopulator may be helpful when writing code that loads properties from a text-source. In fact, the wxPropertyGrid xrc-handler (which may not be currently included in wxWidgets, but probably will be in near future) uses it.
You can use wxPropertyGridInterface::SaveEditableState() and wxPropertyGridInterface::RestoreEditableState() to save and restore user-editable state (selected property, expanded/collapsed properties, selected page, scrolled position, and splitter positions).
Probably the most important event is the Changed event which occurs when value of any property is changed by the user. Use EVT_PG_CHANGED(id,func) in your event table to use it.
For complete list of event types, see wxPropertyGrid class reference.
However, one type of event that might need focused attention is EVT_PG_CHANGING, which occurs just prior property value is being changed by user. You can acquire pending value using wxPropertyGridEvent::GetValue(), and if it is not acceptable, call wxPropertyGridEvent::Veto() to prevent the value change from taking place.
For each property you can specify two different types of help text. First, you can use wxPropertyGridInterface::SetPropertyHelpString() or wxPGProperty::SetHelpString() to set property's help text. Second, you can use wxPGProperty::SetAttribute() to set property's "Hint" attribute.
Difference between hint and help string is that the hint is shown in an empty property value cell, while help string is shown either in the description text box, as a tool tip, or on the status bar, whichever of these is available.
To enable display of help string as tool tips, you must explicitly use the wxPG_EX_HELP_AS_TOOLTIPS extra window style.
There are various ways to make sure user enters only correct values. First, you can use wxValidators similar to as you would with ordinary controls. Use wxPropertyGridInterface::SetPropertyValidator() to assign wxValidator to property.
Second, you can subclass a property and override wxPGProperty::ValidateValue(), or handle wxEVT_PG_CHANGING for the same effect. Both of these ways do not actually prevent user from temporarily entering invalid text, but they do give you an opportunity to warn the user and block changed value from being committed in a property.
Various validation failure options can be controlled globally with wxPropertyGrid::SetValidationFailureBehavior(), or on an event basis by calling wxEvent::SetValidationFailureBehavior(). Here's a code snippet of how to handle wxEVT_PG_CHANGING, and to set custom failure behaviour and message.
There is probably one preference for keyboard handling for every developer out there, and as a conveniency control wxPropertyGrid tries to cater for that. By the default arrow keys are used for navigating between properties, and TAB key is used to move focus between the property editor and the first column. When the focus is in the editor, arrow keys usually no longer work for navigation since they are consumed by the editor.
There are mainly two functions which you can use this customize things, wxPropertyGrid::AddActionTrigger() and wxPropertyGrid::DedicateKey(). First one can be used to set a navigation event to occur on a specific key press and the second is used to divert a key from property editors, making it possible for the grid to use keys normally consumed by the focused editors.
For example, let's say you want to have an ENTER-based editing scheme. That is, editor is focused on ENTER press and the next property is selected when the user finishes editing and presses ENTER again. Code like this would accomplish the task:
wxPG_ACTION_EDIT is prioritized above wxPG_ACTION_NEXT_PROPERTY so that the above code can work without conflicts. For a complete list of available actions, see wxPropertyGrid Action Identifiers.
Here's another trick. Normally the up and down cursor keys are consumed by the focused wxTextCtrl editor and as such can't be used for navigating between properties when that editor is focused. However, using DedicateKey() we can change this so that instead of the cursor keys moving the caret inside the wxTextCtrl, they navigate between adjacent properties. As such:
In this section are presented miscellaneous ways to have custom appearance and behaviour for your properties without all the necessary hassle of sub-classing a property class etc.
Every property can have a small value image placed in front of the actual value text. Built-in example of this can be seen with wxColourProperty and wxImageFileProperty, but for others it can be set using wxPropertyGrid::SetPropertyImage method.
You can set editor control (or controls, in case of a control and button), of any property using wxPropertyGrid::SetPropertyEditor. Editors are passed as wxPGEditor_EditorName, and valid built-in EditorNames are TextCtrl, Choice, ComboBox, CheckBox, TextCtrlAndButton, ChoiceAndButton, SpinCtrl, and DatePickerCtrl. Two last mentioned ones require call to static member function wxPropertyGrid::RegisterAdditionalEditors().
Following example changes wxColourProperty's editor from default Choice to TextCtrlAndButton. wxColourProperty has its internal event handling set up so that button click events of the button will be used to trigger colour selection dialog.
Naturally, creating and setting custom editor classes is a possibility as well. For more information, see wxPGEditor class reference.
SpinCtrl editor can make use of property's "Min", "Max", "Step" and "Wrap" attributes.
See wxPGMultiButton class reference.
wxEVT_COMMAND_BUTTON_CLICKED (corresponds to event table macro EVT_BUTTON): Occurs when editor button click is not handled by the property itself (as is the case, for example, if you set property's editor to TextCtrlAndButton from the original TextCtrl).
Miscellaneous values, often specific to a property type, can be set using wxPropertyGridInterface::SetPropertyAttribute() and wxPropertyGridInterface::SetPropertyAttributeAll() methods.
Attribute names are strings and values wxVariant. Arbitrary names are allowed in order to store values that are relevant to application only and not property grid. Constant equivalents of all attribute string names are provided. Some of them are defined as cached strings, so using these constants can provide for smaller binary size.
For complete list of attributes, see wxPropertyGrid Property Attribute Identifiers.
wxPropertyGridManager is an efficient multi-page version of wxPropertyGrid, which can optionally have tool bar for mode and page selection, and a help text box. For more information, see wxPropertyGridManager class reference.
wxPropertyGridPage is holder of properties for one page in manager. It is derived from wxEvtHandler, so you can subclass it to process page-specific property grid events. Hand over your page instance in wxPropertyGridManager::AddPage().
For more information, see wxPropertyGridPage class reference.
Few things to note:
All properties which parent is category or root can be accessed directly by their base name (ie. name given for property in its constructor). Other properties can be accessed via "ParentsName.BaseName" notation, Naturally, all property names should be unique.
It is possible to have properties with identical label under same parent. However, care must be taken to ensure that each property still has unique (base) name.
There are few points about wxBoolProperty that require further discussion:
wxBoolProperty can be shown as either normal combo box or as a check box. Property attribute wxPG_BOOL_USE_CHECKBOX is used to change this. For example, if you have a wxFlagsProperty, you can set its all items to use check box using the following:
Following will set all individual bool properties in your control to use check box:
Changes from wxTextCtrl based property editors are committed (ie. wxEVT_PG_CHANGED is sent etc.) only when (1) user presser enter, (2) user moves to edit another property, or (3) when focus leaves the grid.
Because of this, you may find it useful, in some apps, to call wxPropertyGrid::CommitChangesFromEditor() just before you need to do any computations based on property grid values. Note that CommitChangesFromEditor() will dispatch wxEVT_PG_CHANGED with ProcessEvent, so any of your event handlers will be called immediately.
If you need to center the splitter, but only once when the program starts, then do not use the wxPG_SPLITTER_AUTO_CENTER window style, but the wxPropertyGrid::CenterSplitter() method. However, be sure to call it after the sizer setup and SetSize calls! (ie. usually at the end of the frame/dialog constructor)
Splitter centering behaviour can be customized using wxPropertyGridInterface::SetColumnProportion(). Usually it is used to set non-equal column proportions, which in essence stops the splitter(s) from being 'centered' as such, and instead just auto-resized.
Splitter position cannot exceed grid size, and therefore setting it during form creation may fail as initial grid size is often smaller than desired splitter position, especially when sizers are being used.
Through sub-classing, these two property classes provide substantial customization features. Subclass wxSystemColourProperty if you want to use wxColourPropertyValue (which features colour type in addition to wxColour), and wxColourProperty if plain wxColour is enough.
Override wxSystemColourProperty::ColourToString() to redefine how colours are printed as strings.
Override wxSystemColourProperty::GetCustomColourIndex() to redefine location of the item that triggers colour picker dialog (default is last).
Override wxSystemColourProperty::GetColour() to determine which colour matches which choice entry.
Version of wxPropertyGrid bundled with wxWidgets 2.9+ has various backward- incompatible changes from version 1.4, which had a stable API and will remain as the last separate branch.
Note that in general any behaviour-breaking changes should not compile or run without warnings or errors.