wxPropertyGrid
|
wxPropertyGrid is a specialized for editing properties such as strings, numbers, flagsets, fonts, and colours. It allows hierarchial, collapsible properties (via so-called categories that can hold child properties), sub-properties, and has strong wxVariant support.
Documentation for wxPython bindings: For a tutorial see the accompanied wxPython readme file and the test_propgrid.py sample. Otherwise, individual member functions should work very much the same as with the C++ wxWidgets, so you'll probably find wxPropertyGrid and wxPropertyGridManager class references handy.
Key Classes:
wxPropertyGrid
wxPropertyGridManager
wxPropertyGridEvent
Header files:
wx/propgrid/propgrid.h: Mandatory when using wxPropertyGrid.
wx/propgrid/advprops.h: For less often used property classes.
wx/propgrid/manager.h: Mandatory when using wxPropertyGridManager.
wx/propgrid/propdev.h: Mandatory when implementing custom property classes.
What's new in wxPropertyGrid 1.4?
Creating and Populating wxPropertyGrid
Categories
Tree-like Property Structure
wxEnumProperty and wxFlagsProperty
Specialized Properties
Iterating through a property container
More About Operating with Properties
Event Handling
Validating Property Values
Populating wxPropertyGrid Automatically
Customizing Individual Cell Appearance
Customizing Properties (without sub-classing)
Using wxPropertyGridManager
Subclassing wxPropertyGrid and wxPropertyGridManager
Miscellaneous Topics
Property Class Descriptions
Using wxPropertyGrid control
Design Notes
Creating New Properties
Creating Custom Property Editor
For comprehensive list of changes and new features, please see the changelog.
For people implementing custom property classes the differences are extensive, so if you are coming from wxPropertyGrid 1.2.x, it is recommended that you take a look.
As seen here, wxPropertyGrid is constructed in the same way as other wxWidgets controls:
(for complete list of new window styles: Additional 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 should be done either via wxPropertyGrid's (or wxPropertyGridManager's) methods, or by acquiring pointer to a property (Append returns a wxPGProperty* or wxPGId, which is typedef for same), and then calling its method. Note however that property's methods generally do not automatically update grid graphics.
Property container functions operating on properties, such as SetPropertyValue or DisableProperty, all accept a special wxPGPropArg, argument which can automatically convert name of a property to a pointer. For instance:
Using pointer is faster, since it doesn't require hash map lookup. Anyway, you can allways get property pointer (wxPGProperty*) as Append/Insert return value, or by calling GetPropertyByName.
Below are samples for using some of the more commong operations. See wxPropertyGridInterface and wxPropertyGrid class references for complete list.
wxPropertyGrid has a hierarchial 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, and SetPropertyLabel also sets label of a category. Note however that sometimes the label of a property category may be referred as caption (for example, there is SetCaptionForegroundColour method that sets text colour of a property category's label).
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 added to it. You may add properties to specific categories by using wxPropertyGrid::Insert or wxPropertyGrid::AppendIn.
Category code sample:
As a new feature in version 1.3.1, basicly any property can have children. There are few limitations, however.
Sample:
wxEnumProperty is used when you want property's (integer or string) value to be selected from a popup list of choices.
Creating wxEnumProperty is 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 label storage, actually stores strings and values. It is used to facilitiate 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. Infact, if you wish to display bitmaps next to labels, your best choice is to use this approach.
If you later need to change choices used by a property, there is function for that as well.
If you want to create your enum properties with simple (label,name,value) constructor, then you need to create a new property class using one of the supplied macro pairs. See Creating New Properties for details.
wxEditEnumProperty is works exactly like wxEnumProperty, except is uses non-readonly combobox as default editor, and value is stored as string when it is not any of the choices.
wxFlagsProperty is similar:
wxFlagsProperty can use wxPGChoices just the same way as wxEnumProperty (and also custom property classes can be created with similar macro pairs). Note: When changing "choices" (ie. flag labels) of wxFlagsProperty, you will need to use SetPropertyChoices - otherwise they 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>.
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 or sub-propeties 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 List of Property Iterator Flags. GetIterator() also accepts other arguments. See wxPropertyGridInterface::GetIterator() for details.
This example reverse-iterates through all visible items:
wxPython Note: Instead of ++ operator, use Next() method, and instead of operator, use GetProperty() method.
GetIterator() only works with wxPropertyGrid and the individual pages of wxPropertyGridManager. In order to iterate through an arbitrary property container, you need to use wxPropertyGridInterface::GetVIterator(). Note however that this virtual iterater is limited to forward iteration.
Getting value of selected wxSystemColourProperty (which value type is derived from wxObject):
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 supplied xrc handler (src/xh_propgrid.cpp) uses it. See that code for more info. NOTE: src/xh_propgrid.cpp is not included in the library by default, to avoid dependency to wxXRC. You will need to add it to your application separately.
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.
The custom event class, wxPropertyGridEvent, has methods to directly access the property that triggered the event.
Here's a small sample:
Another event type you might find useful 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.
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 methods 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.
You can control text colour, background colour, and attached image of each cell in the property grid. Use wxPropertyGridInterface::SetPropertyCell() or wxPGProperty::SetCell() for this purpose.
In addition, it is possible to control these characteristics for wxPGChoices list items. See wxPGChoices::Item() and wxPGChoiceEntry class reference for more info.
In this section are presented miscellaneous ways to have custom appearance and behavior 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 wxValidator for a property using wxPropertyGrid::SetPropertyValidator.
Validator will work just like in wxWidgets (ie. editorControl->SetValidator(validator) is called).
You can set editor control (or controls, in case of a control and button), of any property using wxPropertyGrid::SetPropertyEditor. Editors are passed using wxPG_EDITOR(EditorName) macro, 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", "Wrap" and "MotionSpin" 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 wxPropertyGrid::SetPropertyAttribute and wxPropertyGrid::SetPropertyAttributeAll methods.
Attribute names are strings and values wxVariant. Arbitrary names are allowed inorder to store user values. Constant equivalents of all attribute string names are provided. Some of them are defined as cached strings, so using constants can provide for smaller binary size.
For complete list of attributes, see Property Attributes.
To have all wxBoolProperties to use CheckBox editor instead of Choice, use following (call after bool properties have been added):
wxPropertyGridManager is an efficient multi-page version of wxPropertyGrid, which can optionally have toolbar for mode and page selection, and a help text box.
wxPropertyGridManager inherits from wxPropertyGridInterface, and as such it has most property manipulation functions. However, only some of them affect properties on all pages (eg. GetPropertyByName() and ExpandAll()), while some (eg. Append()) only apply to the currently selected page.
To operate explicitly on properties on specific page, use wxPropertyGridManager::GetPage() to obtain pointer to page's wxPropertyGridPage object.
Visual methods, such as SetCellBackgroundColour and GetNextVisible are only available in wxPropertyGrid. Use wxPropertyGridManager::GetGrid() to obtain pointer to it.
Iteration methods will not work in wxPropertyGridManager. Instead, you must acquire the internal grid (GetGrid()) or wxPropertyGridPage object (GetPage()).
wxPropertyGridManager constructor has exact same format as wxPropertyGrid constructor, and basicly accepts same extra window style flags (albeit also has some extra ones).
Here's some example code for creating and populating a wxPropertyGridManager:
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.
Please note that the wxPropertyGridPage itself only sports subset of wxPropertyGrid API (but unlike manager, this include item iteration). Naturally it inherits from wxPropertyGridMethods and wxPropertyGridState.
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 futher discussion:
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 behavior can be customized using wxPropertyGridInterface::SetColumnProportion(). Usually it is used to set non-equal column proportions, which in essence stops the splitter(s) no longer being 'centered' as such.
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.
Normally only the second column (i.e. the one at column index 1) is editable by user. However, you can make any column editable by calling wxPropertyGrid::MakeColumnEditable(index). For instance, calling that function with index 0 you can make property labels editable.
Events wxEVT_PG_LABEL_EDIT_BEGIN and wxEVT_PG_LABEL_EDIT_ENDING are generated as appropriate. You can veto these events to prevent label editor from (dis)appearing.
Through subclassing, 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.
Here is list of supported preprocessor defines (other than those that relate with wxWidgets core library):
wxPG_INCLUDE_MANAGER: Defines as 0 to exclude wxPropertyGridManager from compilation.
wxPG_INCLUDE_ADVPROPS: Defines as 0 to exclude properties and editors defined in advprops.h and advprops.cpp.
wxPG_USE_WXMODULE: Define as 0 to not use wxModule to manage global variables. This may be needed in cases where wxPropertyGrid is linked as a plugin DLL, or when wxPropertyGrid is linked statically in a DLL.
WXMAKINGLIB_PROPGRID: Define if you are linking wxPropertyGrid statically but wxWidgets itself is DLL.
WXMAKINGDLL_PROPGRID: Define when building wxPropertyGrid as a DLL. This should be automatically defined correctly by the Bakefile-generated makefiles.
wxPG_USE_STL: Define as 1 to let wxPropertyGrid use STL classes in API as much as possible. Default value equals wxUSE_STL.
wxPG_COMPATIBILITY_1_2_0: Define as 1 to make wxPropertyGrid more compatible with the old 1.2.x releases.
wxPG_COMPATIBILITY_1_0_0: Define to make wxPropertyGrid more compatible with the old 1.0.x releases.
Here are descriptions of built-in properties, with attributes (see wxPropertyGrid::SetPropertyAttribute) that apply to them. Note that not all attributes are necessarily here. For complete list, see Property Attributes.
Not an actual property per se, but a header for a group of properties.
Inheritable Class: wxStringProperty
Simple string property. wxPG_STRING_PASSWORD attribute may be used to echo value as asterisks and use wxTE_PASSWORD for wxTextCtrl.
Like wxStringProperty, but converts text to a signed long integer. wxIntProperty seemlessly supports 64-bit integers (ie. wxLongLong).
Like wxIntProperty, but displays value as unsigned int. To set the prefix used globally, manipulate wxPG_UINT_PREFIX string attribute. To set the globally used base, manipulate wxPG_UINT_BASE int attribute. Regardless of current prefix, understands (hex) values starting with both "0x" and "$". wxUIntProperty seemlessly supports 64-bit unsigned integers (ie. wxULongLong).
Like wxStringProperty, but converts text to a double-precision floating point. Default float-to-text precision is 6 decimals, but this can be changed by modifying wxPG_FLOAT_PRECISION attribute.
Represents a boolean value. wxChoice is used as editor control, by the default. wxPG_BOOL_USE_CHECKBOX attribute can be set to true inorder to use check box instead.
Like wxStringProperty, but has a button that triggers a small text editor dialog.
Like wxLongStringProperty, but the button triggers dir selector instead.
Like wxLongStringProperty, but the button triggers file selector instead. Default wildcard is "All files..." but this can be changed by setting wxPG_FILE_WILDCARD attribute (see wxFileDialog for format details). Attribute wxPG_FILE_SHOW_FULL_PATH can be set to false inorder to show only the filename, not the entire path.
Represents a single selection from a list of choices - custom combobox control is used to edit the value.
Represents a bit set that fits in a long integer. wxBoolProperty sub-properties are created for editing individual bits. Textctrl is created to manually edit the flags as a text; a continous sequence of spaces, commas and semicolons is considered as a flag id separator. Note: When changing "choices" (ie. flag labels) of wxFlagsProperty, you will need to use SetPropertyChoices - otherwise they will not get updated properly.
Allows editing of a list of strings in wxTextCtrl and in a separate dialog.
wxDateTime property. Default editor is DatePickerCtrl, altough TextCtrl should work as well. wxPG_DATE_FORMAT attribute can be used to change string wxDateTime::Format uses (altough default is recommended as it is locale-dependant), and wxPG_DATE_PICKER_STYLE allows changing window style given to DatePickerCtrl (default is wxDP_DEFAULT|wxDP_SHOWCENTURY; specifying wxDP_ALLOWNONE enables better support for unspecified property value).
Represents a string that can be freely edited or selected from list of choices - custom combobox control is used to edit the value.
Allows editing a multiple selection from a list of strings. This is property is pretty much built around concept of wxMultiChoiceDialog. It uses wxArrayString value.
Like wxFileProperty, but has thumbnail of the image in front of the filename and autogenerates wildcard from available image handlers.
Useful alternate editor: Choice.
Represents wxColour. wxButton is used to trigger a colour picker dialog.
Represents wxFont. Various sub-properties are used to edit individual subvalues.
Represents wxColour and a system colour index. wxChoice is used to edit the value. Drop-down list has color images.
Represents a wxCursor. wxChoice is used to edit the value. Drop-down list has cursor images under some (wxMSW) platforms.
Sample application has following additional examples of custom properties:
This is a short summary of how a wxPropertyGrid is used (not how it is programmed), or, rather, how it should behave in practice.
Easiest solution for creating an arbitrary property is to subclass an existing, property class that most resembles the intended end result. You may need to include header file wx/propgrid/propdev.h.
For instance:
You can then create a property instance, for instance:
If you want to change editor used, use code like below (continues our sample above).
Note that built-in editors include: TextCtrl, Choice, ComboBox, TextCtrlAndButton, ChoiceAndButton, CheckBox, SpinCtrl, and DatePickerCtrl.
You can change the 'value type' of a property by simply assigning different type of variant with SetValue. It is mandatory to implement wxVariantData class for all data types used as property values. Also, it is further recommended to derive your class from wxPGVariantData (see class documentation for more info).
These are quick methods for creating customized properties.
This custom property will be exactly the same as wxLongStringProperty, except that you can specify a custom code to handle what happens when the button is pressed.
In header:
In source:
FLAGS is either wxPG_NO_ESCAPE (newlines and tabs are not translated to and from escape sequences) or wxPG_ESCAPE (newlines and tabs are transformed into C-string escapes).
There is also WX_PG_IMPLEMENT_STRING_PROPERTY_WITH_VALIDATOR variant which also allows setting up a validator for the property. Like this:
Flags property with custom default value and built-in labels/values.
In header:
In source:
The new property class will have simple (label,name,value) constructor.
Exactly the same as custom FlagsProperty. Simply replace FLAGS with ENUM in macro names to create wxEnumProperty based class instead.
This type of custom property allows selecting different string delimiter (default is '"' on both sides of the string - as in C code), and allows adding custom button into the editor dialog.
In header:
In source:
wxColourProperty/wxSystemColourProperty that can have custom list of colours in dropdown.
Use version that doesn't have _USES_WXCOLOUR in macro names to have wxColourPropertyValue as value type instead of plain wxColour (in this case values array might also make sense).
In header:
In source: