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.
// Necessary header file #include <wx/propgrid/propgrid.h> ... // Assumes code is in frame/dialog constructor // Construct wxPropertyGrid control wxPropertyGrid* pg = new wxPropertyGrid( this, // parent PGID, // id wxDefaultPosition, // position wxDefaultSize, // size // Here are just some of the supported window styles wxPG_AUTO_SORT | // Automatic sorting after items added wxPG_SPLITTER_AUTO_CENTER | // Automatically center splitter until user manually adjusts it // Default style wxPG_DEFAULT_STYLE ); // Window style flags are at premium, so some less often needed ones are // available as extra window styles (wxPG_EX_xxx) which must be set using // SetExtraStyle member function. wxPG_EX_HELP_AS_TOOLTIPS, for instance, // allows displaying help strings as tool tips. pg->SetExtraStyle( wxPG_EX_HELP_AS_TOOLTIPS );
(for complete list of new window styles, see wxPropertyGrid Window Styles)
wxPropertyGrid is usually populated with lines like this:
pg->Append( new wxStringProperty("Label", "Name", "Initial Value") );
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:
// Add int property pg->Append( new wxIntProperty("IntProperty", wxPG_LABEL, 12345678) ); // Add float property (value type is actually double) pg->Append( new wxFloatProperty("FloatProperty", wxPG_LABEL, 12345.678) ); // Add a bool property pg->Append( new wxBoolProperty("BoolProperty", wxPG_LABEL, false) ); // A string property that can be edited in a separate editor dialog. pg->Append( new wxLongStringProperty("LongStringProperty", wxPG_LABEL, "This is much longer string than the " "first one. Edit it by clicking the button.")); // String editor with dir selector button. pg->Append( new wxDirProperty("DirProperty", wxPG_LABEL, ::wxGetUserHome()) ); // wxArrayStringProperty embeds a wxArrayString. pg->Append( new wxArrayStringProperty("Label of ArrayStringProperty", "NameOfArrayStringProp")); // A file selector property. pg->Append( new wxFileProperty("FileProperty", wxPG_LABEL, wxEmptyString) ); // Extra: set wild card for file property (format same as in wxFileDialog). pg->SetPropertyAttribute( "FileProperty", wxPG_FILE_WILDCARD, "All files (*.*)|*.*" );
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:
// Add a file selector property. wxPGPropety* prop = pg->Append( new wxFileProperty("FileProperty", wxPG_LABEL, wxEmptyString) ); // Valid: Set wild card by name pg->SetPropertyAttribute( "FileProperty", wxPG_FILE_WILDCARD, "All files (*.*)|*.*" ); // Also Valid: Set wild card by property pointer pg->SetPropertyAttribute( prop, wxPG_FILE_WILDCARD, "All files (*.*)|*.*" );
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().
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:
// One way to add category (similar to how other properties are added) pg->Append( new wxPropertyCategory("Main") ); // All these are added to "Main" category pg->Append( new wxStringProperty("Name") ); pg->Append( new wxIntProperty("Age",wxPG_LABEL,25) ); pg->Append( new wxIntProperty("Height",wxPG_LABEL,180) ); pg->Append( new wxIntProperty("Weight") ); // Another one pg->Append( new wxPropertyCategory("Attributes") ); // All these are added to "Attributes" category pg->Append( new wxIntProperty("Intelligence") ); pg->Append( new wxIntProperty("Agility") ); pg->Append( new wxIntProperty("Strength") );
wxPGProperty* carProp = pg->Append(new wxStringProperty("Car", wxPG_LABEL, "<composed>")); pg->AppendIn(carProp, new wxStringProperty("Model", wxPG_LABEL, "Lamborghini Diablo SV")); pg->AppendIn(carProp, new wxIntProperty("Engine Size (cc)", wxPG_LABEL, 5707) ); wxPGProperty* speedsProp = pg->AppendIn(carProp, new wxStringProperty("Speeds", wxPG_LABEL, "<composed>")); pg->AppendIn( speedsProp, new wxIntProperty("Max. Speed (mph)", wxPG_LABEL,290) ); pg->AppendIn( speedsProp, new wxFloatProperty("0-100 mph (sec)", wxPG_LABEL,3.9) ); pg->AppendIn( speedsProp, new wxFloatProperty("1/4 mile (sec)", wxPG_LABEL,8.6) ); // This is how child property can be referred to by name pg->SetPropertyValue( "Car.Speeds.Max. Speed (mph)", 300 ); pg->AppendIn(carProp, new wxIntProperty("Price ($)", wxPG_LABEL, 300000) ); // Displayed value of "Car" property is now very close to this: // "Lamborghini Diablo SV; 5707 [300; 3.9; 8.6] 300000"
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:
// // Using wxArrayString // wxArrayString arrDiet; arr.Add("Herbivore"); arr.Add("Carnivore"); arr.Add("Omnivore"); pg->Append( new wxEnumProperty("Diet", wxPG_LABEL, arrDiet) ); // // Using wxChar* array // const wxChar* arrayDiet[] = { wxT("Herbivore"), wxT("Carnivore"), wxT("Omnivore"), NULL }; pg->Append( new wxEnumProperty("Diet", wxPG_LABEL, arrayDiet) );
Here's extended example using values as well:
// // Using wxArrayString and wxArrayInt // wxArrayString arrDiet; arr.Add("Herbivore"); arr.Add("Carnivore"); arr.Add("Omnivore"); wxArrayInt arrIds; arrIds.Add(40); arrIds.Add(45); arrIds.Add(50); // Note that the initial value (the last argument) is the actual value, // not index or anything like that. Thus, our value selects "Omnivore". pg->Append( new wxEnumProperty("Diet", wxPG_LABEL, arrDiet, arrIds, 50));
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.
wxPGChoices chs; chs.Add("Herbivore", 40); chs.Add("Carnivore", 45); chs.Add("Omnivore", 50); // Let's add an item with bitmap, too chs.Add("None of the above", wxBitmap(), 60); pg->Append( new wxEnumProperty("Primary Diet", wxPG_LABEL, chs) ); // Add same choices to another property as well - this is efficient due // to reference counting pg->Append( new wxEnumProperty("Secondary Diet", wxPG_LABEL, chs) );
You can later change choices of property by using wxPGProperty::AddChoice(), wxPGProperty::InsertChoice(), wxPGProperty::DeleteChoice(), and wxPGProperty::SetChoices().
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:
const wxChar* flags_prop_labels[] = { wxT("wxICONIZE"), wxT("wxCAPTION"), wxT("wxMINIMIZE_BOX"), wxT("wxMAXIMIZE_BOX"), NULL }; // this value array would be optional if values matched string indexes long flags_prop_values[] = { wxICONIZE, wxCAPTION, wxMINIMIZE_BOX, wxMAXIMIZE_BOX }; pg->Append( new wxFlagsProperty("Window Style", wxPG_LABEL, flags_prop_labels, flags_prop_values, wxDEFAULT_FRAME_STYLE) );
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.
// Necessary extra header file #include <wx/propgrid/advprops.h> ... // Date property. pg->Append( new wxDateProperty("MyDateProperty", wxPG_LABEL, wxDateTime::Now()) ); // Image file property. Wild card is auto-generated from available // image handlers, so it is not set this time. pg->Append( new wxImageFileProperty("Label of ImageFileProperty", "NameOfImageFileProp") ); // Font property has sub-properties. Note that we give window's font as // initial value. pg->Append( new wxFontProperty("Font", wxPG_LABEL, GetFont()) ); // Colour property with arbitrary colour. pg->Append( new wxColourProperty("My Colour 1", wxPG_LABEL, wxColour(242,109,0) ) ); // System colour property. pg->Append( new wxSystemColourProperty("My SysColour 1", wxPG_LABEL, wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOW)) ); // System colour property with custom colour. pg->Append( new wxSystemColourProperty("My SysColour 2", wxPG_LABEL, wxColour(0,200,160) ) ); // Cursor property pg->Append( new wxCursorProperty("My Cursor", wxPG_LABEL, wxCURSOR_ARROW));
Below is a code example which handles wxEVT_PG_CHANGED event:
void MyWindowClass::OnPropertyGridChanged(wxPropertyGridEvent& event) { wxPGProperty* property = event.GetProperty(); // Do nothing if event did not have associated property if ( !property ) return; // GetValue() returns wxVariant, but it is converted transparently to // wxAny wxAny value = property->GetValue(); // Also, handle the case where property value is unspecified if ( value.IsNull() ) return; // Handle changes in values, as needed if ( property.GetName() == "MyStringProperty" ) OnMyStringPropertyChanged(value.As<wxString>()); else if ( property.GetName() == "MyColourProperty" ) OnMyColourPropertyChanged(value.As<wxColour>()); }
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.
wxPropertyGridIterator it; for ( it = pg->GetIterator(); !it.AtEnd(); it++ ) { wxPGProperty* p = *it; // Do something with the property }
As expected there is also a const iterator:
wxPropertyGridConstIterator it; for ( it = pg->GetIterator(); !it.AtEnd(); it++ ) { const wxPGProperty* p = *it; // Do something with the property }
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:
wxPropertyGridIterator it; for ( it = pg->GetIterator(wxPG_ITERATE_VISIBLE, wxBOTTOM); !it.AtEnd(); it-- ) { wxPGProperty* p = *it; // Do something with the property }
wxPython Note: PropertyGridInterface has some useful pythonic iterators as attributes. Properties
lets you iterate through all items that are not category captions or private children. Items
lets you iterate through everything except private children. Also, there are GetPyIterator() and GetPyVIterator(), which return pythonic iterators instead of normal wxPropertyGridIterator.
If you need to use C++ style iterators in wxPython code, note that 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 (such as entire wxPropertyGridManager), you need to use wxPropertyGridInterface::GetVIterator(). Note however that this virtual iterator is limited to forward iteration.
wxPGVIterator it; for ( it = manager->GetVIterator(); !it.AtEnd(); it.Next() ) { wxPGProperty* p = it.GetProperty(); // Do something with the property }
// This is a static method that initializes *all* built-in type handlers // available, including those for wxColour and wxFont. Refers to *all* // included properties, so when compiling with static library, this // method may increase the executable size noticeably. pg->InitAllTypeHandlers(); // Get contents of the grid as a wxVariant list wxVariant all_values = pg->GetPropertyValues(); // Populate the list with values. If a property with appropriate // name is not found, it is created according to the type of variant. pg->SetPropertyValues( my_list_variant );
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.
void MyForm::OnPropertyGridChanging( wxPropertyGridEvent& event ) { wxPGProperty* property = event.GetProperty(); if ( property == m_pWatchThisProperty ) { // GetValue() returns the pending value, but is only // supported by wxEVT_PG_CHANGING. if ( event.GetValue().GetString() == g_pThisTextIsNotAllowed ) { event.Veto(); return; } } }
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.
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.
void MyFrame::OnPropertyGridChanging(wxPropertyGridEvent& event) { wxPGProperty* property = event.GetProperty(); // You must use wxPropertyGridEvent::GetValue() to access // the value to be validated. wxVariant pendingValue = event.GetValue(); if ( property->GetName() == "Font" ) { // Make sure value is not unspecified if ( !pendingValue.IsNull() ) { wxFont font; font << pendingValue; // Let's just allow Arial font if ( font.GetFaceName() != "Arial" ) { event.Veto(); event.SetValidationFailureBehavior(wxPG_VFB_STAY_IN_PROPERTY | wxPG_VFB_BEEP | wxPG_VFB_SHOW_MESSAGEBOX); } } } }
In addition, it is possible to control these characteristics for wxPGChoices list items. See wxPGChoices class reference for more info.
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:
// Have property editor focus on Enter propgrid->AddActionTrigger( wxPG_ACTION_EDIT, WXK_RETURN ); // Have Enter work as action trigger even when editor is focused propgrid->DedicateKey( WXK_RETURN ); // Let Enter also navigate to the next property propgrid->AddActionTrigger( wxPG_ACTION_NEXT_PROPERTY, WXK_RETURN );
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:
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.
wxPGProperty* colProp = new wxColourProperty("Text Colour"); pg->Append(colProp); pg->SetPropertyEditor(colProp, wxPGEditor_TextCtrlAndButton);
Naturally, creating and setting custom editor classes is a possibility as well. For more information, see wxPGEditor class reference.
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.
Please note that the wxPropertyGridPage itself only sports subset of wxPropertyGrid API (but unlike manager, this include item iteration). Naturally it inherits from wxPropertyGridInterface.
For more information, see wxPropertyGridPage class reference.
pg->SetPropertyAttribute("MyFlagsProperty", wxPG_BOOL_USE_CHECKBOX, true, wxPG_RECURSE);
Following will set all individual bool properties in your control to use check box:
pg->SetPropertyAttributeAll(wxPG_BOOL_USE_CHECKBOX, true);
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.
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.
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.
Note that in general any behaviour-breaking changes should not compile or run without warnings or errors.
![]() |
[ top ] |