I have derived a class FeedItemViewModel from QAbstractListModel.
I have implemented a method which adds items in the list model but I do not know how too update an item which has a specific id.
Here is the code:
void FeedItemViewModel::addFeedItem(FeedItem* feedItem)
{
beginInsertRows(QModelIndex(), rowCount(), rowCount());
m_feedItems.append(feedItem);
endInsertRows();
}
void FeedItemViewModel::updateFeedItem(FeedItem* feedItem)
{
int id = feedItem->id();
auto iter = std::find_if(m_feedItems.begin(), m_feedItems.end(),
[id](FeedItem* item)
{
return item->id() == id;
});
}
Here is the solution I found:
void FeedItemViewModel::updateFeedItem(FeedItem* feedItem)
{
int id = feedItem->id();
auto iter = std::find_if(m_feedItems.begin(), m_feedItems.end(),
[id](FeedItem* item)
{
return item->id() == id;
});
if(iter != m_feedItems.end())
{
int indx = m_feedItems.indexOf(*iter);
m_feedItems[indx] = feedItem;
dataChanged(index(indx), index(indx));
}
}
If you are just updating an item and not replacing it, you could simplify by finding the pointer itself instead of using the id property
void FeedItemViewModel::updateFeedItem(FeedItem *feedItem){
int indx = m_feedItems.indexOf(feedItem);
if(indx != -1){
dataChanged(index(indx), index(indx));
}
}
Related
I'm having trouble figuring out how to delete an item from a list.
Please note that I would like to perform the deletion from the advance() function. This code is just boiled down from my actual project, to try to isolate the error.
#include <iostream>
#include <list>
#include <iterator>
#include <algorithm>
using namespace std;
const int SCT_OSC_FILLED = 11;
class OrderInfo {
private:
std::string id;
public:
OrderInfo(std::string a, int aStatusCode);
std::string key();
int statusCode;
};
OrderInfo::OrderInfo(std::string a, int aStatusCode) {
id = a;
statusCode = aStatusCode;
}
std::string OrderInfo::key() {
return id;
}
std::list <OrderInfo> MasterOrders;
void testList();
void add(OrderInfo ordInfo);
void advance(OrderInfo ordInfo, std::list <OrderInfo> ::iterator& orderIter);
void testList() {
OrderInfo o1("1", 15);
OrderInfo o2("2", 16);
OrderInfo o3("3", SCT_OSC_FILLED);
OrderInfo o4("4", 17);
OrderInfo o5("5", SCT_OSC_FILLED);
OrderInfo o6("6", 18);
add(o1);
add(o1);
add(o2);
add(o3);
add(o4);
add(o5);
add(o6);
for (auto v : MasterOrders)
std::cout << v.key() << "\n";
}
void add(OrderInfo ordInfo) {
// Add to MasterOrders (if not already in list)
bool alreadyInList = false;
std::list <OrderInfo> ::iterator orderIter = MasterOrders.begin();
while (orderIter != MasterOrders.end())
{
OrderInfo oi = *orderIter;
alreadyInList = ordInfo.key() == oi.key();
if (alreadyInList) break;
advance(ordInfo, orderIter);
}
if (!alreadyInList) MasterOrders.push_front(ordInfo);
}
void advance(OrderInfo ordInfo, std::list <OrderInfo> ::iterator& orderIter) {
bool iterate = true;
if (ordInfo.statusCode == SCT_OSC_FILLED) {
orderIter = MasterOrders.erase(orderIter++); // https://stackoverflow.com/a/5265561/270143
iterate = false;
}
if (iterate) orderIter++;
}
int main()
{
testList();
return 0;
}
update: I forgot to state the actual goal
my goal is to just delete SCT_OSC_FILLED ordInfos from within the advance() method (that part is important) and leave the rest. My actual project code does more than what is shown, these names of functions are just made up for this example.. there is more code in them not directly related to manipulating the list (but related to processing OrderInfo) in my actual project. My goal is to leave one copy of o1 in the list as well as o2, o4 and o6 - removing o3 and o5 because they have an SCT_OSC_FILLED OrderInfo.statusCode
So the problem is nothing to do with deletion from a list. Your logic is simply wrong given the stated goal.
You want to delete all SCT_OSC_FILLED items from the list when adding an item but the code you write deletes all items from the list when you add an item with SCT_OSC_FILLED. You are simply testing the wrong thing.
Change this
void advance(OrderInfo ordInfo, std::list <OrderInfo> ::iterator& orderIter) {
bool iterate = true;
if (ordInfo.statusCode == SCT_OSC_FILLED) {
orderIter = MasterOrders.erase(orderIter++);
iterate = false;
}
if (iterate) orderIter++;
}
to this
void advance(OrderInfo ordInfo, std::list <OrderInfo> ::iterator& orderIter) {
bool iterate = true;
if (orderIter->statusCode == SCT_OSC_FILLED) {
orderIter = MasterOrders.erase(orderIter);
iterate = false;
}
if (iterate) orderIter++;
}
Once you make that change you can see that the ordInfo parameter is unused. Add bit more cleanup and you end up with this much simpler function
void advance(std::list <OrderInfo> ::iterator& orderIter) {
if (orderIter->statusCode == SCT_OSC_FILLED) {
orderIter = MasterOrders.erase(orderIter);
}
else {
orderIter++;
}
}
According to cppreference.com, "References and iterators to the erased elements are invalidated." You should get an iterator to the next element, before deleting the current element.
In the same page, cppreference gives an example:
// Erase all even numbers (C++11 and later)
for (std::list<int>::iterator it = c.begin(); it != c.end(); ) {
if (*it % 2 == 0) {
it = c.erase(it);
} else {
++it;
}
}
erase returns an iterator to the next element (end() if the removed element was the last), so "it = c.erase(it);" makes "it" to point to the next element, and there is no need for incrementing the iterator (with ++).
So you could have something like:
void advance(OrderInfo ordInfo, std::list <OrderInfo> ::iterator& orderIter) {
if (ordInfo.statusCode == SCT_OSC_FILLED) {
orderIter = MasterOrders.erase(orderIter);
} else {
orderIter++;
}
}
While implementing LRU cache got this error.
Earlier I was implementing it via maps it works then but somehow even when doing it as vector it does not work.
#include <list>
class LRUCache {
list<pair<int,int>> lru;
int cap;
vector<list<pair<int, int>>::iterator> hash;
public:
LRUCache(int capacity) {
cap = capacity;
for(int i=0;i<=3000;i++)
hash.push_back(nullptr);
}
int get(int key) {
if(hash[(key)]!=nullptr)
{
int v = hash[key]->first;
lru.erase(hash[key]);
lru.push_front({v,key});
hash[key] = lru.begin();
return v;
}
else
return -1;
}
void put(int key, int value) {
if(hash[(key)]!=nullptr)
{
int v = value;
lru.erase(hash[key]);
lru.push_front({v,key});
hash[key] = lru.begin();
}
else if(lru.size()<cap)
{
lru.push_front({value,key});
hash[key] = lru.begin();
}
else
{
lru.push_front({value,key});
hash[key] = lru.begin();
auto it = lru.end();
it--;
hash[(it->second)] = nullptr;
lru.erase(it);
}
}
};
This way does not work either.
vector<list<pair<int, int>>::iterator> hash(3001,NULL);
Can we not create a vector of pointers?
Create an iterator variable, instead of nullptr value, as bellow:
list<pair<int, int>>::iterator emptyIt; // this iterator object refer to nothing
// Using `emptyIt` to initialize the hash
LRUCache(int capacity) {
cap = capacity;
for(int i=0;i<=3000;i++)
hash.push_back(emptyIt);
}
// Using emptyIt instead of nullptr
int get(int key) {
if(hash[(key)]!=emptyIt)
{
int v = hash[key]->first;
lru.erase(hash[key]);
lru.push_front({v,key});
hash[key] = lru.begin();
return v;
}
else
return -1;
}
void put(int key, int value) {
if(hash[(key)]!=emptyIt)
{
int v = value;
lru.erase(hash[key]);
lru.push_front({v,key});
hash[key] = lru.begin();
}
else if(lru.size()<cap)
{
lru.push_front({value,key});
hash[key] = lru.begin();
}
else
{
lru.push_front({value,key});
hash[key] = lru.begin();
auto it = lru.end();
it--;
hash[(it->second)] = emptyIt;
lru.erase(it);
}
}
};
Qt allows you to style GUI using stylesheets. Those use similar selector syntax to regular CSS. I would like to use those selectors in code to reach specific Widgets, similarly to the way jQuery works. For example:
SomeQtCSSMagic::resolveSelector("QPushButton#okButton");
Is this possible? If not, is there at least code I could copy-paste from Qt library and edit to suit my needs?
At the moment, Qt offers no official support for that. But it's not all that hard to do using plain C++ code.
Your selector translates to:
for (auto top : qApp->topLevelWidgets()) {
auto widgets = top->findChildren<QWidget*>("okButton");
widgets << top;
for (auto widget : widgets)
if (widget->inherits("QPushButton"))
qDebug() << "found" << widget;
}
If you find such code tedious, you can leverage the private Qt code. The CSS parser interface is in src/gui/text/qcssparser_p.h. Apart from the parser, you also need some code to use the parsed selector to find the widget. Namely, you have to implement a QCss::StyleSelector for a node that points to a QObject. That's done by QStyleSheetStyleSelector in src/widgets/styles/qstylesheetstyle.cpp, but that's a local class that's not exported, so you do have some copypasta to deal with that.
Once you have implemented a QCss::StyleSelector, here as QObjectStyleSelector, obtaining the widgets that the selector applies to is easy. You have to iterate over all widgets, and see if the CSS machinery has any rules for a given node, assuming a dummy stylesheet consisting of your selector and an empty body {}. This approach supports all selectors that the style sheets support, with exception of selecting on a widget's style:
QWidgetList select(const QString & selector) {
static QHash<QString, StyleSheet> cache;
QWidgetList result;
QObjectStyleSelector oSel;
auto it = cache.find(selector);
if (it == cache.end()) {
StyleSheet styleSheet;
Parser parser(selector + "{}");
if (!parser.parse(&styleSheet))
return result;
it = cache.insert(selector, styleSheet);
}
oSel.styleSheets.append(*it);
for (auto top : qApp->topLevelWidgets()) {
auto widgets = top->findChildren<QWidget*>();
widgets << top;
for (auto widget : widgets) {
StyleSelector::NodePtr n { widget };
auto rules = oSel.styleRulesForNode(n);
if (!rules.isEmpty()) result << widget;
}
}
return result;
}
This code above is not "distracted" by any style sheets that might exist on the widgets - it takes into account their side effects (e.g. property changes), but otherwise ignores them.
You can test it as follows:
int main(int argc, char ** argv) {
QApplication app{argc, argv};
QDialog dialog;
QPushButton button{"OK", &dialog};
button.setObjectName("okButton");
button.setStyleSheet("color: red");
auto dialog_l = QWidgetList() << &dialog;
auto button_l = QWidgetList() << &button;
auto all_l = button_l + dialog_l;
Q_ASSERT(select("QPushButton#okButton") == button_l);
Q_ASSERT(select("QDialog QPushButton") == button_l);
Q_ASSERT(select("QDialog") == dialog_l);
Q_ASSERT(select("QDialog, QPushButton") == all_l);
}
The copy-pasta precedes the above:
// https://github.com/KubaO/stackoverflown/tree/master/questions/css-selector-35129103
#include <QtWidgets>
#include <private/qcssparser_p.h>
using namespace QCss;
// FROM src/widgets/styles/qstylesheetstyle.cpp
#define OBJECT_PTR(node) (static_cast<QObject*>((node).ptr))
static inline QObject *parentObject(const QObject *obj)
{
if (qobject_cast<const QLabel *>(obj) && qstrcmp(obj->metaObject()->className(), "QTipLabel") == 0) {
QObject *p = qvariant_cast<QObject *>(obj->property("_q_stylesheet_parent"));
if (p)
return p;
}
return obj->parent();
}
class QObjectStyleSelector : public StyleSelector
{
public:
QObjectStyleSelector() { }
QStringList nodeNames(NodePtr node) const Q_DECL_OVERRIDE
{
if (isNullNode(node))
return QStringList();
const QMetaObject *metaObject = OBJECT_PTR(node)->metaObject();
#ifndef QT_NO_TOOLTIP
if (qstrcmp(metaObject->className(), "QTipLabel") == 0)
return QStringList(QLatin1String("QToolTip"));
#endif
QStringList result;
do {
result += QString::fromLatin1(metaObject->className()).replace(QLatin1Char(':'), QLatin1Char('-'));
metaObject = metaObject->superClass();
} while (metaObject != 0);
return result;
}
QString attribute(NodePtr node, const QString& name) const Q_DECL_OVERRIDE
{
if (isNullNode(node))
return QString();
auto obj = OBJECT_PTR(node);
auto value = obj->property(name.toLatin1());
if (!value.isValid()) {
if (name == QLatin1String("class")) {
auto className = QString::fromLatin1(obj->metaObject()->className());
if (className.contains(QLatin1Char(':')))
className.replace(QLatin1Char(':'), QLatin1Char('-'));
return className;
}
}
if(value.type() == QVariant::StringList || value.type() == QVariant::List)
return value.toStringList().join(QLatin1Char(' '));
else
return value.toString();
}
bool nodeNameEquals(NodePtr node, const QString& nodeName) const Q_DECL_OVERRIDE
{
if (isNullNode(node))
return false;
auto metaObject = OBJECT_PTR(node)->metaObject();
#ifndef QT_NO_TOOLTIP
if (qstrcmp(metaObject->className(), "QTipLabel") == 0)
return nodeName == QLatin1String("QToolTip");
#endif
do {
const ushort *uc = (const ushort *)nodeName.constData();
const ushort *e = uc + nodeName.length();
const uchar *c = (const uchar *)metaObject->className();
while (*c && uc != e && (*uc == *c || (*c == ':' && *uc == '-'))) {
++uc;
++c;
}
if (uc == e && !*c)
return true;
metaObject = metaObject->superClass();
} while (metaObject != 0);
return false;
}
bool hasAttributes(NodePtr) const Q_DECL_OVERRIDE
{ return true; }
QStringList nodeIds(NodePtr node) const Q_DECL_OVERRIDE
{ return isNullNode(node) ? QStringList() : QStringList(OBJECT_PTR(node)->objectName()); }
bool isNullNode(NodePtr node) const Q_DECL_OVERRIDE
{ return node.ptr == 0; }
NodePtr parentNode(NodePtr node) const Q_DECL_OVERRIDE
{ NodePtr n; n.ptr = isNullNode(node) ? 0 : parentObject(OBJECT_PTR(node)); return n; }
NodePtr previousSiblingNode(NodePtr) const Q_DECL_OVERRIDE
{ NodePtr n; n.ptr = 0; return n; }
NodePtr duplicateNode(NodePtr node) const Q_DECL_OVERRIDE
{ return node; }
void freeNode(NodePtr) const Q_DECL_OVERRIDE
{ }
};
// END FROM
#cssparser-35129103.pro
QT = widgets gui-private
CONFIG += c++11
TARGET = cssparser-35129103
TEMPLATE = app
SOURCES += main.cpp
I have two C++ functions in a class:
void Attribute::setIndex(int inIndex) {
if (inIndex < 0) {
index = 0;
}
else if (inIndex >= MAX_NUM_ATTRIBUTES) {
index = MAX_NUM_ATTRIBUTES - 1;
}
else {
index = inIndex;
}
}
and
int Attribute::getValueWithinRange(int value) {
value = setIndex(value);
return value;
}
The second function is supposed to use setIndex to set 'value' to the correct number and return it. However, since the first function is a void function, i cannot simply pas the value in the way i did above. Should i do pass by reference or are there any suggestions? Thank you very much.
I would like just to note, that if you are learning C++, you should try to learn model cases first, sometimes rushing examples is not the best way, but there we go:
Change the setIndex to return int, my favorite;
int Attribute::setIndex(int inIndex)
{
if (inIndex < 0)
{
index = 0;
}
else if (inIndex >= MAX_NUM_ATTRIBUTES)
{
index = MAX_NUM_ATTRIBUTES - 1;
}
else
{
index = inIndex;
}
return index;
}
int Attribute::getValueWithinRange(int value)
{
value = setIndex(value);
return value;
}
Change the getValueWithinRange to return index, both methods are in one class, they share the access to index;
int Attribute::getValueWithinRange(int value)
{
setIndex(value);
return index;
}
Giving it reference would work, but you can not set reference to null unless using a trick and it would require unnecessarily another method, so pointer makes it less messy:
int Attribute::setIndex(int inIndex, int* ret_index = nullptr)
{
if (inIndex < 0)
{
index = 0;
}
else if (inIndex >= MAX_NUM_ATTRIBUTES)
{
index = MAX_NUM_ATTRIBUTES - 1;
}
else
{
index = inIndex;
}
if (ret_index != nullptr) *ret_index = index;
return index;
}
int Attribute::getValueWithinRange(int value)
{
int retvalue;
setIndex(value); // use it like this when returning value is not needed
setIndex(value, &retvalue);
return retvalue;
}
info:
We are trying to create a property whose sub properties may be added/removed depending on the value of another sub property.
An example of this could be an plant object. This object has one property which will be a drop down consisting of types of plants, lets say (daisy, daffodil, and venus fly trap). If venus is selected, I would like to have a property show up below called avgFlyIntake but if daffodil is selected this property should disappear.
example:
Plant
type venus
avgFlyI 2.0
avgHight 3.0
Or
Plant
type daffodil
avgHight 8.0
//Fly Property gone or grayed out.
Edit: Essentially plant is a property of another model that I guess could be called livingThing. The property's show up in a hierarchical fashion in a 2 column table. I'd like the plant properties to be dynamically hidden if it is possible.
c++ src:
PlantProperty::PlantProperty(const QString& name /*= QString()*/, QObject* propertyObject /*= 0*/, QObject* parent /*= 0*/)
: Property(name, propertyObject, parent)
{
m_type = new Property("id", this, this);
m_avgFlyIntake = new Property("avgFlyIntake", this, this);
m_avgHeight = new Property("avgHeight", this, this);
//setEditorHints("...");
}
enum PlantProperty::getType() const{
return value().value<Plant>().getType();
}
void PlantProperty::setType(enum enabled){
//if enum changed show and hide relevant properties associated with selection
Property::setValue(QVariant::fromValue(Plant(...)));
}
c++ h:
class PlantProperty : public Property{
Q_OBJECT
/**/
Q_PROPERTY(int type READ getType WRITE setType DESIGNABLE true USER true)
Q_PROPERTY(float avgFlyIntake READ getavgFlyIntake WRITE setAvgFlyIntake DESIGNABLE true USER ture)
Q_PROPERTY(float avgHeight READ getavgHeight WRITE setavgHeihgt DESIGNABLE true USER true)
public:
PlantProperty (const QString&name = QString(), QObject* propertyObject = 0, QObject* parent = 0);
QVariant data(const QModelIndex &index, int role) const;
int rowCount(const QModelIndex &parent = QModelIndex()) const;
QVariant value(int role = Qt::UserRole) const;
virtual void setValue(const QVariant& value);
void setEditorHints(const QString& hints);
int getType() const;
void setType(int id);
private:
QString parseHints(const QString& hints, const QChar component);
Property* type;
Property* avgFlyIntake;
Property* avgHeight;
};
Q_DECLARE_METATYPE(Plant)
#endif //PLANTPROPERTY_H
q property model:
// *************************************************************************************************
//
// QPropertyEditor v 0.3
//
// --------------------------------------
// Copyright (C) 2007 Volker Wiendl
// Acknowledgements to Roman alias banal from qt-apps.org for the Enum enhancement
//
//
// The QPropertyEditor Library is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation version 3 of the License
//
// The Horde3D Scene Editor is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
// *************************************************************************************************
#include "QPropertyModel.h"
#include "Property.h"
#include "EnumProperty.h"
#include <QtGui/QApplication>
#include <QtCore/QMetaProperty>
#include <QtGui/QItemEditorFactory>
struct PropertyPair
{
PropertyPair(const QMetaObject* obj, QMetaProperty property) : Property(property), Object(obj) {}
QMetaProperty Property;
const QMetaObject* Object;
bool operator==(const PropertyPair& other) const {return QString(other.Property.name()) == QString(Property.name());}
};
QPropertyModel::QPropertyModel(QObject* parent /*= 0*/) : QAbstractItemModel(parent)
{
m_rootItem = new Property("Root",0, this);
}
QPropertyModel::~QPropertyModel()
{
}
QModelIndex QPropertyModel::index ( int row, int column, const QModelIndex & parent /*= QModelIndex()*/ ) const
{
Property *parentItem = m_rootItem;
if (parent.isValid())
parentItem = static_cast<Property*>(parent.internalPointer());
if (row >= parentItem->children().size() || row < 0)
return QModelIndex();
return createIndex(row, column, parentItem->children().at(row));
}
QModelIndex QPropertyModel::parent ( const QModelIndex & index ) const
{
if (!index.isValid())
return QModelIndex();
Property *childItem = static_cast<Property*>(index.internalPointer());
Property *parentItem = qobject_cast<Property*>(childItem->parent());
if (!parentItem || parentItem == m_rootItem)
return QModelIndex();
return createIndex(parentItem->row(), 0, parentItem);
}
int QPropertyModel::rowCount ( const QModelIndex & parent /*= QModelIndex()*/ ) const
{
Property *parentItem = m_rootItem;
if (parent.isValid())
parentItem = static_cast<Property*>(parent.internalPointer());
return parentItem->children().size();
}
int QPropertyModel::columnCount ( const QModelIndex & /*parent = QModelIndex()*/ ) const
{
return 2;
}
QVariant QPropertyModel::data ( const QModelIndex & index, int role /*= Qt::DisplayRole*/ ) const
{
if (!index.isValid())
return QVariant();
Property *item = static_cast<Property*>(index.internalPointer());
switch(role)
{
case Qt::ToolTipRole:
case Qt::DecorationRole:
case Qt::DisplayRole:
case Qt::EditRole:
if (index.column() == 0)
return item->objectName().replace('_', ' ');
if (index.column() == 1)
return item->value(role);
case Qt::BackgroundRole:
if (item->isRoot()) return QApplication::palette("QTreeView").brush(QPalette::Normal, QPalette::Button).color();
break;
};
return QVariant();
}
// edit methods
bool QPropertyModel::setData ( const QModelIndex & index, const QVariant & value, int role /*= Qt::EditRole*/ )
{
if (index.isValid() && role == Qt::EditRole)
{
Property *item = static_cast<Property*>(index.internalPointer());
item->setValue(value);
emit dataChanged(index, index);
return true;
}
return false;
}
Qt::ItemFlags QPropertyModel::flags ( const QModelIndex & index ) const
{
if (!index.isValid())
return Qt::ItemIsEnabled;
Property *item = static_cast<Property*>(index.internalPointer());
// only allow change of value attribute
if (item->isRoot())
return Qt::ItemIsEnabled;
else if (item->isReadOnly())
return Qt::ItemIsDragEnabled | Qt::ItemIsSelectable;
else
return Qt::ItemIsDragEnabled | Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsEditable;
}
QVariant QPropertyModel::headerData ( int section, Qt::Orientation orientation, int role /*= Qt::DisplayRole*/ ) const
{
if (orientation == Qt::Horizontal && role == Qt::DisplayRole)
{
switch (section)
{
case 0:
return tr("Name");
case 1:
return tr("Value");
}
}
return QVariant();
}
QModelIndex QPropertyModel::buddy ( const QModelIndex & index ) const
{
if (index.isValid() && index.column() == 0)
return createIndex(index.row(), 1, index.internalPointer());
return index;
}
void QPropertyModel::addItem(QObject *propertyObject)
{
// first create property <-> class hierarchy
QList<PropertyPair> propertyMap;
QList<const QMetaObject*> classList;
const QMetaObject* metaObject = propertyObject->metaObject();
do
{
int count = metaObject->propertyCount();
for (int i=0; i<count; ++i)
{
QMetaProperty property = metaObject->property(i);
if( property.isUser() ) // Hide Qt specific properties
{
PropertyPair pair(metaObject, property);
int index = propertyMap.indexOf(pair);
if (index != -1)
propertyMap[index] = pair;
else
propertyMap.push_back(pair);
}
}
classList.push_front(metaObject);
}
while ((metaObject = metaObject->superClass())!=0);
QList<const QMetaObject*> finalClassList;
// remove empty classes from hierarchy list
foreach(const QMetaObject* obj, classList)
{
bool keep = false;
foreach(PropertyPair pair, propertyMap)
{
if (pair.Object == obj)
{
keep = true;
break;
}
}
if (keep)
finalClassList.push_back(obj);
}
// finally insert properties for classes containing them
int i=rowCount();
Property* propertyItem = 0;
beginInsertRows( QModelIndex(), i, i + finalClassList.count() );
foreach(const QMetaObject* metaObject, finalClassList)
{
// Set default name of the hierarchy property to the class name
QString name = metaObject->className();
// Check if there is a special name for the class
int index = metaObject->indexOfClassInfo(qPrintable(name));
if (index != -1)
name = metaObject->classInfo(index).value();
// Create Property Item for class node
propertyItem = new Property(name, 0, m_rootItem);
foreach(PropertyPair pair, propertyMap)
{
// Check if the property is associated with the current class from the finalClassList
if (pair.Object == metaObject)
{
QMetaProperty property(pair.Property);
Property* p = 0;
if (property.type() == QVariant::UserType && !m_userCallbacks.isEmpty())
{
QList<QPropertyEditorWidget::UserTypeCB>::iterator iter = m_userCallbacks.begin();
while( p == 0 && iter != m_userCallbacks.end() )
{
p = (*iter)(property.name(), propertyObject, propertyItem);
++iter;
}
}
if( p == 0){
if(property.isEnumType()){
p = new EnumProperty(property.name(), propertyObject, propertyItem);
} else {
p = new Property(property.name(), propertyObject, propertyItem);
}
}
int index = metaObject->indexOfClassInfo(property.name());
if (index != -1)
p->setEditorHints(metaObject->classInfo(index).value());
}
}
}
endInsertRows();
if( propertyItem ) addDynamicProperties( propertyItem, propertyObject );
}
void QPropertyModel::updateItem ( QObject* propertyObject, const QModelIndex& parent /*= QModelIndex() */ )
{
Property *parentItem = m_rootItem;
if (parent.isValid())
parentItem = static_cast<Property*>(parent.internalPointer());
if (parentItem->propertyObject() != propertyObject)
parentItem = parentItem->findPropertyObject(propertyObject);
if (parentItem) // Indicate view that the data for the indices have changed
{
QModelIndex itemIndex = createIndex(parentItem->row(), 0, static_cast<Property*>(parentItem));
dataChanged(itemIndex, createIndex(parentItem->row(), 1, static_cast<Property*>(parentItem)));
QList<QByteArray> dynamicProperties = propertyObject->dynamicPropertyNames();
QList<QObject*> childs = parentItem->parent()->children();
int removed = 0;
for(int i = 0; i < childs.count(); ++i )
{
QObject* obj = childs[i];
if( !obj->property("__Dynamic").toBool() || dynamicProperties.contains( obj->objectName().toLocal8Bit() ) )
continue;
beginRemoveRows(itemIndex.parent(), i - removed, i - removed);
++removed;
delete obj;
endRemoveRows();
}
addDynamicProperties(static_cast<Property*>(parentItem->parent()), propertyObject);
}
}
void QPropertyModel::addDynamicProperties( Property* parent, QObject* propertyObject )
{
// Get dynamic property names
QList<QByteArray> dynamicProperties = propertyObject->dynamicPropertyNames();
QList<QObject*> childs = parent->children();
// Remove already existing properties from list
for(int i = 0; i < childs.count(); ++i )
{
if( !childs[i]->property("__Dynamic").toBool() ) continue;
int index = dynamicProperties.indexOf( childs[i]->objectName().toLocal8Bit() );
if( index != -1)
{
dynamicProperties.removeAt(index);
continue;
}
}
// Remove invalid properites and those we don't want to add
for(int i = 0; i < dynamicProperties.size(); ++i )
{
QString dynProp = dynamicProperties[i];
// Skip properties starting with _ (because there may be dynamic properties from Qt with _q_ and we may
// have user defined hidden properties starting with _ too
if( dynProp.startsWith("_") || !propertyObject->property( qPrintable(dynProp) ).isValid() )
{
dynamicProperties.removeAt(i);
--i;
}
}
if( dynamicProperties.empty() ) return;
QModelIndex parentIndex = createIndex(parent->row(), 0, static_cast<Property*>(parent));
int rows = rowCount(parentIndex);
beginInsertRows(parentIndex, rows, rows + dynamicProperties.count() - 1 );
// Add properties left in the list
foreach(QByteArray dynProp, dynamicProperties )
{
QVariant v = propertyObject->property(dynProp);
Property* p = 0;
if( v.type() == QVariant::UserType && !m_userCallbacks.isEmpty() )
{
QList<QPropertyEditorWidget::UserTypeCB>::iterator iter = m_userCallbacks.begin();
while( p == 0 && iter != m_userCallbacks.end() )
{
p = (*iter)(dynProp, propertyObject, parent);
++iter;
}
}
if( p == 0 ) p = new Property(dynProp, propertyObject, parent);
p->setProperty("__Dynamic", true);
}
endInsertRows();
}
void QPropertyModel::clear()
{
beginRemoveRows(QModelIndex(), 0, rowCount());
delete m_rootItem;
m_rootItem = new Property("Root",0, this);
endRemoveRows();
}
void QPropertyModel::registerCustomPropertyCB(QPropertyEditorWidget::UserTypeCB callback)
{
if ( !m_userCallbacks.contains(callback) )
m_userCallbacks.push_back(callback);
}
void QPropertyModel::unregisterCustomPropertyCB(QPropertyEditorWidget::UserTypeCB callback)
{
int index = m_userCallbacks.indexOf(callback);
if( index != -1 )
m_userCallbacks.removeAt(index);
}
QObject has a dynamic property system, so you do not need to manually declare any properties at all. It'd be easy to map such objects to an item view. But it seems like the use of a QObject is overkill.
It seems like you'd be completely covered by using a QStandardItemModel and its items, arranged in a tree. An item could be either a plant, or a plant's property.