Properties editor design pattern? - c++

Warning: This is super in-depth. I understand if you don't even want to read this, this is mostly for me to sort out my thought process.
Okay, so here's what I'm trying to do. I've got these objects:
When you click on one (or select several) it should display their properties on the right (as shown). When you edit said properties it should update the internal variables immediately.
I'm trying to decide on the best way to do this. I figure the selected objects should be stored as a list of pointers. It's either that, or have an isSelected bool on each object, and then iterate over all of them, ignoring the non-selected ones, which is just inefficient. So we click on one, or select several, and then the selectedObjects list is populated. We then need to display the properties. To keep things simple for the time being, we'll assume that all objects are of the same type (share the same set of properties). Since there aren't any instance-specific properties, I figure we should probably store these properties as static variables inside the Object class. Properties basically just have a name (like "Allow Sleep"). There is one PropertyManager for each type of property (int,bool,double). PropertyManagers store all the values for properties of their respective type (this is all from the Qt API). Unfortunately, because PropertyManagers are required to create Properties I can't really decouple the two. I suppose this means that I have to place the PropertyManagers with the Properties (as static variables). This means we have one set of properties, and one set of property managers to manage all the variables in all the objects. Each property manager can only have one callback. That means this callback has to update all the properties of its respective type, for all objects (a nested loop). This yields something like this (in pseudo-code):
function valueChanged(property, value) {
if(property == xPosProp) {
foreach(selectedObj as obj) {
obj->setXPos(value);
}
} else if(property == ...
Which already bothers me a little bit, because we're using if statements where we shouldn't need them. The way around this would be to create a different property manager for every single property, so that we can have unique callbacks. This also means we need two objects for each property, but it might be a price worth paying for cleaner code (I really don't know what the performance costs are right now, but as I know you'll also say -- optimize when it becomes a problem). So then we end up with a ton of callbacks:
function xPosChanged(property, value) {
foreach(selectedObj as obj) {
obj->setXPos(value);
}
}
Which eliminates the entire if/else garbage but adds a dozen more event-listeners. Let's assume I go with this method. So now we had a wad of static Properties, along with their corresponding static PropertyManagers. Presumably I'd store the list of selected objects as Object::selectedObjects too since they're used in all the event callbacks, which logically belong in the object class. So then we have a wad of static event callbacks too. That's all fine and dandy.
So now when you edit a property, we can update the interal variables for all the selected objects via the event callback. But what happens when the internal variable is updated via some other means, how do we update the property? This happens to be a physics simulator, so all the objects will have many of their variables continuously updated. I can't add callbacks for these because the physics is handled by another 3rd party library. I guess this means I just have to assume all the variables have been changed after each time step. So after each time step, I have to update all the properties for all the selected objects. Fine, I can do that.
Last issue (I hope), is what values should we display when multiple objects are selected an there is an inconsistency? I guess my options are to leave it blank/0 or display a random object's properties. I don't think one option is much better than the other, but hopefully Qt provides a method to highlight such properties so that I can at least notify the user. So how do I figure out which properties to "highlight"? I guess I iterate over all the selected objects, and all their properties, compare them, and as soon as there is a mismatch I can highlight it. So to clarify, upon selected some objects:
add all objects to a selectedObjects list
populate the properties editor
find which properties have identical values and update the editor appropriately
I think I should store the properties in a list too so that I can just push the whole list onto the properties editor rather than adding each property individually. Should allow for more flexibility down the road I think.
I think that about covers it... I'm still not certain how I feel about having so many static variables, and a semi-singleton class (the static variables would be initialized once when the first object is created I guess). But I don't see a better solution.
Please post your thoughts if you actually read this. I guess that's not really a question, so let me rephrase for the haters, What adjustments can I make to my suggested design-pattern to yield cleaner, more understandable, or more efficient code? (or something along those lines).
Looks like I need to clarify. By "property" I mean like "Allow Sleeping", or "Velocity" -- all objects have these properties -- their VALUES however, are unique to each instance. Properties hold the string that needs to be displayed, the valid range for the values, and all the widget info. PropertyManagers are the objects that actually hold the value. They control the callbacks, and the value that's displayed. There is also another copy of the value, that's actually used "internally" by the other 3rd party physics library.
Trying to actually implement this madness now. I have an EditorView (the black area drawing area in the image) which catches the mouseClick event. The mouseClick events then tells the physics simulator to query all the bodies at the cursor. Each physics body stores a reference (a void pointer!) back to my object class. The pointers get casted back to objects get pushed onto a list of selected objects. The EditorView then sends out a signal. The EditorWindow then catches this signal and passes it over to the PropertiesWindow along with the selected objects. Now the PropertiesWindow needs to query the objects for a list of properties to display... and that's as far as I've gotten so far. Mind boggling!
The Solution
/*
* File: PropertyBrowser.cpp
* Author: mark
*
* Created on August 23, 2009, 10:29 PM
*/
#include <QtCore/QMetaProperty>
#include "PropertyBrowser.h"
PropertyBrowser::PropertyBrowser(QWidget* parent)
: QtTreePropertyBrowser(parent), m_variantManager(new QtVariantPropertyManager(this)) {
setHeaderVisible(false);
setPropertiesWithoutValueMarked(true);
setIndentation(10);
setResizeMode(ResizeToContents);
setFactoryForManager(m_variantManager, new QtVariantEditorFactory);
setAlternatingRowColors(false);
}
void PropertyBrowser::valueChanged(QtProperty *property, const QVariant &value) {
if(m_propertyMap.find(property) != m_propertyMap.end()) {
foreach(QObject *obj, m_selectedObjects) {
obj->setProperty(m_propertyMap[property], value);
}
}
}
QString PropertyBrowser::humanize(QString str) const {
return str.at(0).toUpper() + str.mid(1).replace(QRegExp("([a-z])([A-Z])"), "\\1 \\2");
}
void PropertyBrowser::setSelectedObjects(QList<QObject*> objs) {
foreach(QObject *obj, m_selectedObjects) {
obj->disconnect(this);
}
clear();
m_variantManager->clear();
m_selectedObjects = objs;
m_propertyMap.clear();
if(objs.isEmpty()) {
return;
}
for(int i = 0; i < objs.first()->metaObject()->propertyCount(); ++i) {
QMetaProperty metaProperty(objs.first()->metaObject()->property(i));
QtProperty * const property
= m_variantManager->addProperty(metaProperty.type(), humanize(metaProperty.name()));
property->setEnabled(metaProperty.isWritable());
m_propertyMap[property] = metaProperty.name();
addProperty(property);
}
foreach(QObject *obj, m_selectedObjects) {
connect(obj, SIGNAL(propertyChanged()), SLOT(objectUpdated()));
}
objectUpdated();
}
void PropertyBrowser::objectUpdated() {
if(m_selectedObjects.isEmpty()) {
return;
}
disconnect(m_variantManager, SIGNAL(valueChanged(QtProperty*, QVariant)),
this, SLOT(valueChanged(QtProperty*, QVariant)));
QMapIterator<QtProperty*, QByteArray> i(m_propertyMap);
bool diff;
while(i.hasNext()) {
i.next();
diff = false;
for(int j = 1; j < m_selectedObjects.size(); ++j) {
if(m_selectedObjects.at(j)->property(i.value()) != m_selectedObjects.at(j - 1)->property(i.value())) {
diff = true;
break;
}
}
if(diff) setBackgroundColor(topLevelItem(i.key()), QColor(0xFF,0xFE,0xA9));
else setBackgroundColor(topLevelItem(i.key()), Qt::white);
m_variantManager->setValue(i.key(), m_selectedObjects.first()->property(i.value()));
}
connect(m_variantManager, SIGNAL(valueChanged(QtProperty*, QVariant)),
this, SLOT(valueChanged(QtProperty*, QVariant)));
}
With a big thanks to TimW

Did you have a look at Qt's (dynamic) property system?
bool QObject::setProperty ( const char * name, const QVariant & value );
QVariant QObject::property ( const char * name ) const
QList<QByteArray> QObject::dynamicPropertyNames () const;
//Changing the value of a dynamic property causes a
//QDynamicPropertyChangeEvent to be sent to the object.
function valueChanged(property, value) {
foreach(selectedObj as obj) {
obj->setProperty(property, value);
}
}
Example
This is an incomplete example to give you my idea about the property system.
I guess SelectableItem * selectedItem must be replaced with a list of items in your case.
class SelectableItem : public QObject
{
Q_OBJECT
Q_PROPERTY(QString name READ name WRITE setName );
Q_PROPERTY(int velocity READ velocity WRITE setVelocity);
public:
QString name() const { return m_name; }
int velocity() const {return m_velocity; }
public slots:
void setName(const QString& name)
{
if(name!=m_name)
{
m_name = name;
emit update();
}
}
void setVelocity(int value)
{
if(value!=m_velocity)
{
m_velocity = value;
emit update();
}
}
signals:
void update();
private:
QString m_name;
int m_velocity;
};
class MyPropertyWatcher : public QObject
{
Q_OBJECT
public:
MyPropertyWatcher(QObject *parent)
: QObject(parent),
m_variantManager(new QtVariantPropertyManager(this)),
m_propertyMap(),
m_selectedItem(),
!m_updatingValues(false)
{
connect(m_variantManager, SIGNAL(valueChanged(QtProperty*, QVariant)), SLOT(valueChanged(QtProperty*,QVariant)));
m_propertyMap[m_variantManager->addProperty(QVariant::String, tr("Name"))] = "name";
m_propertyMap[m_variantManager->addProperty(QVariant::Int, tr("Velocity"))] = "velocity";
// Add mim, max ... to the property
// you could also add all the existing properties of a SelectableItem
// SelectableItem item;
// for(int i=0 ; i!=item.metaObject()->propertyCount(); ++i)
// {
// QMetaProperty metaProperty(item.metaObject()->property(i));
// QtProperty *const property
// = m_variantManager->addProperty(metaProperty.type(), metaProperty.name());
// m_propertyMap[property] = metaProperty.name()
// }
}
void setSelectedItem(SelectableItem * selectedItem)
{
if(m_selectedItem)
{
m_selectedItem->disconnect( this );
}
if(selectedItem)
{
connect(selectedItem, SIGNAL(update()), SLOT(itemUpdated()));
itemUpdated();
}
m_selectedItem = selectedItem;
}
private slots:
void valueChanged(QtProperty *property, const QVariant &value)
{
if(m_updatingValues)
{
return;
}
if(m_selectedItem && m_map)
{
QMap<QtProperty*, QByteArray>::const_iterator i = m_propertyMap.find(property);
if(i!=m_propertyMap.end())
m_selectedItem->setProperty(m_propertyMap[property], value);
}
}
void itemUpdated()
{
m_updatingValues = true;
QMapIterator<QtProperty*, QByteArray> i(m_propertyMap);
while(i.hasNext())
{
m_variantManager->next();
m_variantManager->setValue(
i.key(),
m_selectedItem->property(i.value()));
}
m_updatingValues = false;
}
private:
QtVariantPropertyManager *const m_variantManager;
QMap<QtProperty*, QByteArray> m_propertyMap;
QPointer<SelectableItem> m_selectedItem;
bool m_updatingValues;
};

Calm down, your code has not O(n^2) complextity. You have a nested loop, but only one counts to N (the number of objects), the other counts to a fixed number of properties, which is not related to N. So you have O(N).
For the static variables, you write "there aren't any instance-specific properties", later you write about updates of the individual properties of your objects, which are exactly instance-specific properties. Maybe you are confusing the "class Properties" (which is of course shared among all properties) with the individual properties? So I think you don't need static members at all.
Do you want to display changes to the objects only if they appear, or do you want a continuos display? If your hardware is able to handle the latter, I would recommend going that way. In that case, you have to iterate over all objects anyway and update them along the way.
Edit: The difference is that in the former (update on change) the drawing is initiated by the operation of changing the values, for example a object movement. For the latter, a continuos display, you would add a QTimer, which fires say 60 times a second and calls a SLOT(render()) which does the actual rendering of all objects. Depending on the rate of changes this may actually be faster. And it is probably easier to implement.
Another possibilty is let Qt handle the whole drawing, using a Graphics View, which handles the objects-to-draw internally in a very efficient tree structure. Take a look at
http://doc.trolltech.com/4.5/graphicsview.html
If you want to display only the changes, you could use individual callbacks for each properties value. Each time the value of a property is changed (in this case making the properties vlaues private and using setSomeThing(value)), you call the update function with an emit(update()). If you are absolutly concernd about emit being slow, you could use "real" callbacks via function pointers, but I don't recommend that, Qt's connect/signal/slot is so much easier to use. And the overhead is in most cases really neglible.

Related

Most efficient way to check for messages in array

I'm currently working on a chess-like game in c++ and was wondering if there were any pattern or good programming ways to check for messages between classes.
In my problem I have two classes, a boardSquare- and a GameBoard-class (BoardSquareManager). The boardsquare has functionality that when you click a square a boolean value will be set to true meaning the boardSquare has been clicked. Currently in the GameBoard-class I have an array of BoardSquares and in order to check if one boardsquare has been clicked I go through every BoardSquare each tick and see if anyone has been clicked, it looks like this.
void AGameBoard::CheckMessages()
{
for (int i = 0; i < 64; i++)
{
if (BoardSquareArray[i]->GetWasClicked())
{
iClickedTile = BoardSquareArray[i]->GetSquareNum();
BoardSquareArray[i]->DeactivateClick();
bTileWasClicked = true;
}
}
}
In my opinion it feels unnecessary to have to look through the entire array all the time just so I can get information if a tile has been clicked or not, do you know any better way of doing this on?
I appreciate all answers!
Have considered the Observer pattern? The classic Design Patterns book from E. Gamma contains a lot patterns which come from implementing GUI applications. Other patterns which are probably interesting are Command (do want to undo moves?), Decorator, Chain of Command, Composite, Strategy, Template Method. I would definitely recommend to read the book.
For now I have gone with making a static class which has a queue. I use this class to send messages from the BoardSquare to the Gameboard. (Making a static class might not be the "best" solution in long term goals but since this is a prototype I was figuring it might work out for now)
Code for Static MessageClass:
/*
* Public variables
*/
static void SendMsgToBoard(int& tile) { TileNumbers.push_back(tile); }
static int& RecieveMsgFromSquare() { return TileNumbers.front(); }
static void SquareMsgRecieved() { TileNumbers.pop_front(); }
static bool IsEmpty() { return TileNumbers.empty(); }
private:
/*
* Private Variables
*/
static std::deque<int> TileNumbers;
New Code for Boardsquare:
messagePasser::SendMsgToBoard(iSquareNum);
New Code for Gameboard:
if (!MessagePasser::IsEmpty())
{
if (IsTileOccupied)
{
//Do stuff...
}
else
//Do Other Stuff...
MessagePasser::SquareMsgRecieved();
}
Make some std::vector or std::stack and push there click events with coordinates of tile which was clicked. You can also make some onClick method which takes pointer do AGameBoard and sent to it message about clicked tile.
Search something on the internet about events handling.

C++ Builder derived TComboBox to have Items by default

A VCL component newbie here, so pardon me if this is a stupid question...
I'm trying to make a TComboBox component with default items in it upon dropped onto the form, i.e. a TMonthComboBox that will have the list of months in its Items list, when dropped on the form.
I've found that trying to access the Items property during Construction will result in a "Control '' has no parent window" error if I try to drop such combobox on the form.
here is (part of) the constructor:
__fastcall TMonthCombo::TMonthCombo(TComponent *Owner):TComboBox(Owner)
{
this->Style = csDropDownList; // this is okay
this->Items->Add("January"); // This is causing problem
}
I figured that the problem is stemming from the fact that the Items property is not available yet at this point of the construction.
Is there anyway to make sure the component is ready to accept values into its Items property, within the component source code itself (i.e. not adding the list items in the Properties Editor at design time)?
Before anyone tells me to "Just add the items in your Application code at run time", I have to explain that this ComboBox will be used quite frequently in many places, and Month selection is just a simple example I used to explain the problem, the actual values I want to put in the ComboBox is much more varied and most of the time, dynamic in nature. It also have to response to the user selection in varied ways.
I have tried the run-time way, but it's getting very tedious. That's why I'm making it into a component, so that it will handle itself without me having to repeatedly input multiple versions of codes just to populate the ComboBoxes.
Thanks for any help.
Edit: After tried manlio's solution, the ComboBox has an odd look in run-time:
The ComboBox has double image at run time. What have I done wrong?
__fastcall TYearCombo::TYearCombo(TComponent* Owner) : TComboBox(Owner), init_items(true)
{
}
//---------------------------------------------------------------------------
void __fastcall TYearCombo::CreateWnd()
{
unsigned short yr, mn, dy;
this->Width = 90;
this->Style = csDropDownList;
this->DropDownCount = 11;
TDate d = Today();
d.DecodeDate(&yr, &mn, &dy);
year = yr;
if (init_items)
{
init_items = false;
TComboBox::CreateWnd();
Items->BeginUpdate();
for(int i=year-5; i<=year+5; i++)
{
Items->Add(IntToStr(i));
}
this->ItemIndex = 5;
Items->EndUpdate();
}
}
//---------------------------------------------------------------------------
You can try this:
Override the CreateWnd virtual method and add a init_items private data member:
class TMonthCombo : public TComboBox
{
// ...
protected:
virtual void __fastcall CreateWnd();
private:
bool init_items;
// ...
};
Set the init_items flag:
TMonthCombo::TMonthCombo(TComponent *Owner) : TComboBox(Owner),
init_items(true)
{
// ...
}
Inside CreateWnd you can add new items:
void __fastcall TMonthCombo::CreateWnd()
{
TComboBox::CreateWnd();
if (init_items)
{
init_items = false;
Items->BeginUpdate();
Items->Add("January");
// ...
Items->EndUpdate();
}
}
Further notes:
"Control has no parent" in Create ComboBox (TComboBox requires an allocated HWND in order to store strings in its Items property).
simply cast the constructor's Owner parameter to TWinControl and assign the result to the component's Parent property isn't a solution:
TMonthCombo::TMonthCombo(TComponent *Owner) : TComBoBox(Owner)
{
Parent = static_cast<TWinControl *>(Owner);
// ...
}
the assignment solves the "Control has no parent window error" but creates another problem: the form is always the component's parent (you cannot add the form to a different container).

Share array or list between C++ and QML via property

There's a list of unsigned ints in C++ class. The list can be modified inside the class in some way. There's a QML object that has to use this list. How should I declare the list to make the object able to use the values from the list and after changing the content of the list inside C++ get appropriate values in QML?
Currently the list is defined as:
QVariantList cards;
Q_PROPERTY(QVariantList cards MEMBER cards NOTIFY setChanged)
void setChanged ( QVariantList const &cards );
But QML takes only cards initial value (empty list) and does not "notice" any changes inside it later on.
The need for NOTIFY signal is optional. I guess it is for when we need to deliberately let QML know that the data is ready but the data will be consumed when it READs data. Aside from this we can almost always avoid programming NOTIFY. I even do rootItem->setProperty("propertyName", value) for occasional push in of new value to QML especially if there onPropertyNameChanged handler is ready.
The below will likely do what you want. Or it is required and adding NOTIFY to that won't hurt as well but adds 'inoperability'.
class MyMsgBoard : public QObject
{
public:
Q_PROPERTY(QVariantList cards READ cards WRITE setCards)
const QVariantList & cards() const { return qvList; }
void setCards(const QVariantList & v) { qvList = v; }
private:
QVariantList qvList;
};
More detailed explanation. I use message board concept from there.

generalization of mapping a multi-variable/layer system

I wrote an application with C++ / QT that communicates with a device to read/write its variables, puts/gets them in a struct and presents them in a gui for both viewing/editing purposes.
1) The device comes with a sample c code that also defines the communication protocol (in a very bad way) like:
#define VALUE_1 0x12345678
#define VALUE_2 0xDEADBEEF
#define MY_DEVICE_VAR (VALUE_1 << 4) & (VALUE_2 >> 6)
#define MY_DEVICE_VAR_1 (MY_DEVICE_VAR & (VALUE_1 << 2)
#define MY_DEVICE_VAR_2 (MY_DEVICE_VAR & (VALUE_2 << 4)
#define MY_DEVICE_VAR_2 (MY_DEVICE_VAR & (VALUE_2 << 4)
// .. and 300 more lines like above
So the variable VAR_1 is represented with: MY_DEVICE_VAR_1.
2) I've got a struct that holds all variables of the device:
struct MyDeviceData
{
int var1;
double var2;
char var3;
bool var4;
.
.
};
It's basically a storage for / a projection of the data read from the device. There are 4 different types of POD variables.
3) Finally my gui has gui elements to show and edit the instance of MyDeviceData
class MyGuI
{
QLineEdit var1;
QLineEdit var2;
QComboBox var3;
QCheckBox var4;
.
.
};
Now my questions are:
1) I'm doing the mapping of MY_DEVICE_VAR1 -> MyDeviceData::var1 -> MyGUI::var1 with if and switch/case statements which I'm not proud with. What would be a better "programmatic" way to do the mapping?
2) When the value of a gui element gets changed, I want to send only updated value to the card. besides overriding the handler functions of events like "textChanged, selectedIndexChanged" etc. Are there any "smarter" methods? (QSignalMapper?)
3) In this kind of project, is it possible to generalize whole drudge work? (a code-generator tool? templates?)
I have recently faced exactly the same problem, although I was the one designing the device, its firmware, and the communication protocol as well.
I think that one must use model/view to keep one's sanity.
I have all the variables as elements in a data model class deriving from QAbstractTableModel. That's because there's a fixed number of simple parameters (rows), and they are the same per each device (column). Quite soon, though, I'll have to move to a tree model, because some parameters internally are structured as lists, vectors or matrices, and it'd be helpful to expose them to views directly as such, and not merely as formatted strings.
The model class also has some convenience getters/setters so that you don't have to refer to the parameters by their row/column. The row/column access via a QModelIndex is only for use by the views.
I chose to use the UserRole for directly represented values (mostly doubles in SI units), and Display and Edit roles to present formatted/scaled data to the widgets.
For non-view controls, one needs a binder object. QDataWidgetMapper is provided by Qt, and you should ideally use it.
A while ago I didn't notice that there was the widget mapper, so I wrote custom a binder object (deriving from QObject), that gets instantiated for each GUI control, to bind a certain index of the model to a non-view Qt control widget. Another approach would be to use QListViews, have a proxy model per each view that exposes just one element, and properly assign delegates. This would introduce a lot of overhead, though. The binder object approach is quite lightweight.
The model-view approach also enables one to easily factor out the up-to-dateness indication of each control.
When the application is first started up, the model can indicate (via a dedicated role), that the values are invalid. This can put an x-cross or barber pole on the control to clearly indicate that there is no valid value there.
When the device is active, and the user modifies a control, a different role can indicate that the value was changed in the model, but not propagated to the device yet.
When the device communications code picks up the change from the model and commits it to the device, it can tell the model about it, and the view (the biner, really) will automatically pick it up and update the control.
Adding a Model * clone() const method to the model, or adding serialization/deserialization operators, allows you to trivially take snapshots of the model, and implement Undo/Redo, Commit/Revert, etc.
Relevant snippets of the binder are here:
// constructor
Binder::Binder(QAbstractItemModel * model_, const QModelIndex & index_, QObject * object) :
QObject(object),
model(model_),
index(index_),
sourceRole(Qt::DisplayRole),
property(""),
target(object),
lockout(false)
{
Q_ASSERT(index.isValid());
// replicate for each type of control
if (qobject_cast<QDoubleSpinBox*>(object)) {
connect(object, SIGNAL(valueChanged(double)), SLOT(doubleSpinBoxGet(double)));
connect(index.model(), SIGNAL(dataChanged(QModelIndex, QModelIndex)), SLOT(doubleSpinBoxSet(QModelIndex, QModelIndex)));
}
else if (....)
}
// getter/setter for QDoubleSpinBox
void Binder::doubleSpinBoxGet(double val)
{
if (lockout) return;
QScopedValueRollback<bool> r(lockout);
lockout = true;
model->setData(index, val, sourceRole);
}
void Binder::doubleSpinBoxSet(const QModelIndex & tl, const QModelIndex & br)
{
if (lockout) return;
if (! isTarget(tl, br)) return;
QScopedValueRollback<bool> r(lockout);
lockout = true;
if (! index.data().canConvert<double>()) return;
qobject_cast<QDoubleSpinBox*>(target)->setValue(index.data(sourceRole).toDouble());
}
// helper
bool Binder::isTarget(const QModelIndex & topLeft, const QModelIndex & bottomRight)
{
return topLeft.parent() == bottomRight.parent()
&& topLeft.parent() == index.parent()
&& topLeft.row() <= index.row()
&& topLeft.column() <= index.column()
&& bottomRight.row() >= index.row()
&& bottomRight.column() >= index.column();
}

Hierachical data in TreeViews and TreeView updating technique

I have lots of (hierachical) data that I show in a TreeView (could be around 20K items or more, including children items). The peculiar problem with my data is that each object shown in the treeview can exist in many treeview items. What I mean by that is that I might have an hierarchy like this one:
Item_A -> Item_B -> ItemC
Item_B -> Item_C
ItemC
Lets assume that Item_A contains Item_B which contains Item_C as it is shown above. This means that my list will also show the hierarchy of Item_B and Item_C. Consider now that something happens to an an object shown as Item_B (e.g name change). Then of course both items
must be updated. Consider now thousands of items in the treeview with complex hierarchies. What strategy would you use to update the treeview? Speed is of course the main concern here but also ease of use and maintenance. Currently I hold internal mappings of list items to objects and vice-versa to find and update items quickly. Is that a correct strategy? By recreating the list after each update I can throw lots of code away, but I wouldn't know which item paths were expanded or collapsed. How could I solve this problem? Should I store expanded paths in an internal container?
Thank you.
PS: Programming language is C++, and GUI lib is QT3.
I did something similar long time ago, using the windows TreeView common control.
What I did was set the CUSTOMDRAW flag, keep a single instance of each possible different node and make each node point to this instance: The 3 Item_C nodes would each have a pointer to the same unique Item_C instance.
So, when I change the data on Item_C I only needed to Invoke InvalidateRect() on the 3 Item_C nodes in order to reflect the changes done on the (single) changed data.
I suppose you could apply the same strategy here.
Use Qt4 model/view if you can use Qt4 in your project.
You will have to write your own model which can be tedious if you've never done so, but once setup you can reference/update multiple instances of the same object easily. Selections/Multiple selection can be handled too.
I'm not a big fan of Qt's model/view implementation (given model/view/controller design pattern is quite old) but it helps to organize data in gUIs
Disable updates using widget->setUpdatesEnabled(false), then edit all you want, and then renable it with widget->setUpdatesEnabled(true).
See the Qt documentation.
I solved a similar problem using the wxWidgets tree control. I used a singleton reference counter to track the objects I was putting in the control, and an iterator to traverse them. Here's an example.
class ReferenceCounter
{
public:
// Singleton pattern. Implementation left up to you.
static ReferenceCounter& get();
void add(const TreeData& data) {
mCounter[data.getId()].push_back(&data);
}
void remove(const TreeData& data) {
const CounterType::const_iterator itr = mCounter.find(data.getId());
if (itr != mCounter.end()) {
ItemType& items = itr->second;
items.erase(std::remove(items.begin(), items.end(), &data), items.end());
if (items.empty()) {
mCounter.erase(itr);
}
}
}
typedef std::vector<TreeData*> ItemType;
ItemType::iterator begin(const TreeData& data) {
const CounterType::const_iterator itr = mCounter.find(data.getId());
if (itr != mCounter.end()) {
return itr->second.begin();
}
// Else condition handling left up to you.
}
ItemType::iterator end(const TreeData& data) {
const CounterType::const_iterator itr = mCounter.find(data.getId());
if (itr != mCounter.end()) {
return itr->second.end();
}
// Else condition handling left up to you.
}
private:
typedef std::map<int, ItemType> CounterType;
CounterType mCounter;
};
class TreeData
{
public:
TreeData() { ReferenceCounter::get().add(*this); }
~TreeData() { ReferenceCounter::get().remove(*this); }
// Get database rows or whatever your tree is tracking.
int getId() const;
};
So given any TreeData, you can look up all the other TreeData's with matching ids in the reference counter. This makes it easy and fast keeping names and stuff up to date. Our tree handles over 1,000,000 nodes without a problem. In my implementation, I wrapped the iteration stuff up in a boost::iterator_facade class for easier use.