I would like override the QObject::setProperty(const char*, QVariant) because when I call this method with a QVariant which contains a QVariantList the method fail because it doesn't convert the QVariantList to QList<UnknownType>.
Any suggestions?
EDIT
I have the abstract class Node which contains
Context* _context;
QMap<QString, QString> _inputsPersisted;
QMap<QString, QString> _outputsPersisted;
The Node class has also a virtual void runImplementation() and the method void run() like this :
void Node::run()
{
//get inputs from Context
for(QMap<QString, QString>::iterator it = _inputsPersisted.begin() ; it != _inputsPersisted.end() ; ++it )
{
QVariant attribute = property(it.key().toStdString().c_str());
if(!attribute.isValid())
{
qWarning() << QObject::tr("%1:%2: Node::run:%3: the property %4 does not exist.").arg(__FILE__).arg(__LINE__).arg(_id.toString()).arg(it.key());
}
else
{
QVariant v = _context->getDataPersisted(it.value());
if(!v.isValid())
qWarning() << QObject::tr("%1:%2: Node::run:%3: %4 is not in the context.").arg(__FILE__).arg(__LINE__).arg(_id.toString()).arg(it.value());
else
if(v.type() != attribute.type())
qWarning() << QObject::tr("%1:%2: Node::run:%3: %4 and %5 have not the same type.").arg(__FILE__).arg(__LINE__).arg(_id.toString()).arg(it.key()).arg(it.value());
else
if(!setProperty(it.key().toStdString().c_str(), v))
qWarning() << QObject::tr("%1:%2: Node::run:%3: the property %4 have not been setted.").arg(__FILE__).arg(__LINE__).arg(_id.toString()).arg(it.key());
}
}
runImplementation();
//set outputs in the Context
for(QMap<QString, QString>::iterator it = _outputsPersisted.begin() ; it != _outputsPersisted.end() ; ++it )
{
QVariant attribute = property(it.key().toStdString().c_str());
if(!attribute.isValid())
{
qWarning() << QObject::tr("%1:%2: Node::run:%3: the property %4 does not exist.").arg(__FILE__).arg(__LINE__).arg(_id.toString()).arg(it.key());
}
else
{
_context->setDataPersisted(it.value(), attribute);
}
}
}
The Context class is like this :
class Context : public QObject
{
Q_OBJECT
public:
Context(Context* parent = NULL) : : _parent(parent){}
void setDataPersisted(QString name, QVariant value)
{
if(_parent != NULL && _parent->exist(name))
_parent->setDataPersisted(name, value);
else
{
if(_stack.contains(name))
_stack.insert(name, value);
else
_stack.insert(name, value);
}
}
QVariant getDataPersisted(QString name)
{
QVariant v;
QMap<QString, QVariant>::iterator it = _stack.find(name);
if(it != _stack.end())
v.setValue(it.value());
else
if(_parent != NULL)
v.setValue(_parent->getDataPersisted(name));
return v;
}
private:
bool exist(QString name)
{
bool contains = _stack.contains(name);
return contains || ((_parent != NULL) && (_parent->exist(name)));
}
private:
Context * _parent;
QMap<QString, QVariant> _stack;
};
With this a Node child class can put and get some variables in her Context, and this, only by declare her properties and initialize the _inputsPersisted and _outputsPersisted. All the logic is done by the Node class.
Now I would like add a mechanism. I would like manipulate list in a Context and do a append.
For this, I modify the Context::setDataPersisted method:
void setDataPersisted(QString name, QVariant value)
{
if(_parent != NULL && _parent->exist(name))
_parent->setDataPersisted(name, value);
else
{
if(_stack.contains(name) && _stack.find(name)->value().canConvert(QVariant::List))
{
QVariantList toChange = qvariant_cast<QVariantList>(_stack.find(name)->value());
toChange.append(value);
_stack.insert(name, toChange );
}
else
_stack.insert(name, value);
}
}
With this, after a setDataPersited, another setDataPersisted (to "append") and a getDataPersisted the data's list are corrupted.
Use Q_DECLARE_METATYPE macro to register QVariantList withing Qt metatype system. This will allow storing QVariantList as QVariant
Q_DECLARE_METATYPE(QVariantList);
...
QVariantList var;
QVariant v = QVariant::fromValue<QVariantList>( var );
QVariantList lst = v.value<QVariantList>();
To convert QList<SomeType> to QVariantList:
QList<SomeType> lst1;
...
QVariantList lst2;
for (const SomeType& st : lst1)
lst2.append( QVariant::fromValue<SomeType>( st ) );
To convert QVariantList to QList<SomeType> :
QVariantList lst2;
...
QList<SomeType> lst1;
for (const QVariant& st : lst2)
lst2.append( st.value<SomeType>() );
Edit 1:
auto it = _stack.find(name);
if (_stack.end() == it) {
it = _stack.insert( name, QVariant::fromValue<QVariantList>(QVariantList()) );
}
QVariantList toChange = it->value().value<QVariantList>();
toChange.append(value);
_stack.insert(name, QVariant::fromValue<QVariantList>(toChange) );
Related
I'm using a QTableView to view some data from sql database.
the structure is as follows :
QSqlQueryModel
subclass of QSortFilterProxyModel that's used to filter data through search box
QTableView and it's model is the proxy model.
Sometimes when I search and the FilterAcceptsRow is called, the view doesn't load the data, surprisingly when I resize the window or click on the header to sort it, the data gets loaded !
bool ProxyModel::filterAcceptsRow(int source_row,
const QModelIndex &source_parent) const
{
QModelIndex indName = sourceModel()->index(source_row,
7, source_parent);
QModelIndex indNumber= sourceModel()->index(source_row,
6, source_parent);
QModelIndex indAgency = sourceModel()->index(source_row,
0, source_parent);
QModelIndex indStartDate = sourceModel()->index(source_row,2,source_parent);
QModelIndex indEndDate = sourceModel()->index(source_row,1,source_parent);
if (searchBy == 0) // search by name
{
if(sourceModel()->data(indName).toString().contains(name_))
return true;
else
return false;
}
else if( searchBy == 1) // search by number
{
if(sourceModel()->data(indNumber).toString().toLower().contains(number_.toLower()))
return true;
else
return false;
}
else if (searchBy == 2) // search by agency
{
return agencyList.indexOf(sourceModel()->data(indAgency).toString()) == agency_ ;
}
else if (searchBy == 3) // search By date
{
if (sourceModel()->data(indStartDate).toDate() >= start_ &&
sourceModel()->data(indEndDate).toDate() <= end_)
return true;
}
return false;
}
Is there someway to get this working properly ?
I found the fix for that issue, It turns out that the QSortFilterProxyModel does not load all the data until you scroll the QTableView down, then it starts to load the rest of the data.
and that might be a good thing if there is a lot of data, so it's on by default.
I got it working the way i needed by using
bool QAbstractItemModel::canFetchMore(const QModelIndex &parent) const
and
void QAbstractItemModel::fetchMore(const QModelIndex &parent)
after each call for invalidateFilter();
I call them to fetch all the data
while (canFetchMore(sourceModel()->index(rowCount()-1,0)))
{
fetchMore(sourceModel()->index(rowCount()-1,0));
}
Here is a working snippet from my project
#include "qqmlsortfilterproxymodel.h"
#include <QtQml>
#include <algorithm>
#include "filter.h"
#include "sorter.h"
QQmlSortFilterProxyModel::QQmlSortFilterProxyModel(QObject *parent) :
QSortFilterProxyModel(parent)
{
connect(this, &QAbstractProxyModel::sourceModelChanged, this, &QQmlSortFilterProxyModel::updateRoles);
connect(this, &QAbstractItemModel::modelReset, this, &QQmlSortFilterProxyModel::updateRoles);
connect(this, &QAbstractItemModel::rowsInserted, this, &QQmlSortFilterProxyModel::countChanged);
connect(this, &QAbstractItemModel::rowsRemoved, this, &QQmlSortFilterProxyModel::countChanged);
connect(this, &QAbstractItemModel::modelReset, this, &QQmlSortFilterProxyModel::countChanged);
connect(this, &QAbstractItemModel::layoutChanged, this, &QQmlSortFilterProxyModel::countChanged);
setDynamicSortFilter(true);
}
int QQmlSortFilterProxyModel::count() const
{
return rowCount();
}
const QString& QQmlSortFilterProxyModel::filterRoleName() const
{
return m_filterRoleName;
}
void QQmlSortFilterProxyModel::setFilterRoleName(const QString& filterRoleName)
{
if (m_filterRoleName == filterRoleName)
return;
m_filterRoleName = filterRoleName;
updateFilterRole();
Q_EMIT filterRoleNameChanged();
}
QString QQmlSortFilterProxyModel::filterPattern() const
{
return filterRegExp().pattern();
}
void QQmlSortFilterProxyModel::setFilterPattern(const QString& filterPattern)
{
QRegExp regExp = filterRegExp();
if (regExp.pattern() == filterPattern)
return;
regExp.setPattern(filterPattern);
QSortFilterProxyModel::setFilterRegExp(regExp);
Q_EMIT filterPatternChanged();
}
QQmlSortFilterProxyModel::PatternSyntax QQmlSortFilterProxyModel::filterPatternSyntax() const
{
return static_cast<PatternSyntax>(filterRegExp().patternSyntax());
}
void QQmlSortFilterProxyModel::setFilterPatternSyntax(QQmlSortFilterProxyModel::PatternSyntax patternSyntax)
{
QRegExp regExp = filterRegExp();
QRegExp::PatternSyntax patternSyntaxTmp = static_cast<QRegExp::PatternSyntax>(patternSyntax);
if (regExp.patternSyntax() == patternSyntaxTmp)
return;
regExp.setPatternSyntax(patternSyntaxTmp);
QSortFilterProxyModel::setFilterRegExp(regExp);
Q_EMIT filterPatternSyntaxChanged();
}
const QVariant& QQmlSortFilterProxyModel::filterValue() const
{
return m_filterValue;
}
void QQmlSortFilterProxyModel::setFilterValue(const QVariant& filterValue)
{
if (m_filterValue == filterValue)
return;
m_filterValue = filterValue;
invalidateFilter();
Q_EMIT filterValueChanged();
}
const QString& QQmlSortFilterProxyModel::sortRoleName() const
{
return m_sortRoleName;
}
void QQmlSortFilterProxyModel::setSortRoleName(const QString& sortRoleName)
{
if (m_sortRoleName == sortRoleName)
return;
m_sortRoleName = sortRoleName;
updateSortRole();
Q_EMIT sortRoleNameChanged();
}
bool QQmlSortFilterProxyModel::ascendingSortOrder() const
{
return m_ascendingSortOrder;
}
void QQmlSortFilterProxyModel::setAscendingSortOrder(bool ascendingSortOrder)
{
if (m_ascendingSortOrder == ascendingSortOrder)
return;
m_ascendingSortOrder = ascendingSortOrder;
Q_EMIT ascendingSortOrderChanged();
invalidate();
}
QQmlListProperty<Filter> QQmlSortFilterProxyModel::filters()
{
return QQmlListProperty<Filter>(this, &m_filters,
&QQmlSortFilterProxyModel::append_filter,
&QQmlSortFilterProxyModel::count_filter,
&QQmlSortFilterProxyModel::at_filter,
&QQmlSortFilterProxyModel::clear_filters);
}
QQmlListProperty<Sorter> QQmlSortFilterProxyModel::sorters()
{
return QQmlListProperty<Sorter>(this, &m_sorters,
&QQmlSortFilterProxyModel::append_sorter,
&QQmlSortFilterProxyModel::count_sorter,
&QQmlSortFilterProxyModel::at_sorter,
&QQmlSortFilterProxyModel::clear_sorters);
}
void QQmlSortFilterProxyModel::classBegin()
{
}
void QQmlSortFilterProxyModel::componentComplete()
{
m_completed = true;
for (const auto& filter : m_filters)
filter->proxyModelCompleted();
invalidate();
sort(0);
}
QVariant QQmlSortFilterProxyModel::sourceData(const QModelIndex& sourceIndex, const QString& roleName) const
{
int role = sourceModel()->roleNames().key(roleName.toUtf8());
return sourceData(sourceIndex, role);
}
QVariant QQmlSortFilterProxyModel::sourceData(const QModelIndex &sourceIndex, int role) const
{
return sourceModel()->data(sourceIndex, role);
}
int QQmlSortFilterProxyModel::roleForName(const QString& roleName) const
{
return roleNames().key(roleName.toUtf8(), -1);
}
QVariantMap QQmlSortFilterProxyModel::get(int row) const
{
QVariantMap map;
QModelIndex modelIndex = index(row, 0);
QHash<int, QByteArray> roles = roleNames();
for (QHash<int, QByteArray>::const_iterator it = roles.begin(); it != roles.end(); ++it)
map.insert(it.value(), data(modelIndex, it.key()));
return map;
}
QVariant QQmlSortFilterProxyModel::get(int row, const QString& roleName) const
{
return data(index(row, 0), roleForName(roleName));
}
QModelIndex QQmlSortFilterProxyModel::mapToSource(const QModelIndex& proxyIndex) const
{
return QSortFilterProxyModel::mapToSource(proxyIndex);
}
int QQmlSortFilterProxyModel::mapToSource(int proxyRow) const
{
QModelIndex proxyIndex = index(proxyRow, 0);
QModelIndex sourceIndex = mapToSource(proxyIndex);
return sourceIndex.isValid() ? sourceIndex.row() : -1;
}
QModelIndex QQmlSortFilterProxyModel::mapFromSource(const QModelIndex& sourceIndex) const
{
return QSortFilterProxyModel::mapFromSource(sourceIndex);
}
int QQmlSortFilterProxyModel::mapFromSource(int sourceRow) const
{
QModelIndex proxyIndex;
if (QAbstractItemModel* source = sourceModel()) {
QModelIndex sourceIndex = source->index(sourceRow, 0);
proxyIndex = mapFromSource(sourceIndex);
}
return proxyIndex.isValid() ? proxyIndex.row() : -1;
}
bool QQmlSortFilterProxyModel::filterAcceptsRow(int source_row, const QModelIndex& source_parent) const
{
if (!m_completed)
return true;
QModelIndex sourceIndex = sourceModel()->index(source_row, 0, source_parent);
bool valueAccepted = !m_filterValue.isValid() || ( m_filterValue == sourceModel()->data(sourceIndex, filterRole()) );
bool baseAcceptsRow = valueAccepted && QSortFilterProxyModel::filterAcceptsRow(source_row, source_parent);
baseAcceptsRow = baseAcceptsRow && std::all_of(m_filters.begin(), m_filters.end(),
[=, &source_parent] (Filter* filter) {
return filter->filterAcceptsRow(sourceIndex);
}
);
return baseAcceptsRow;
}
bool QQmlSortFilterProxyModel::lessThan(const QModelIndex& source_left, const QModelIndex& source_right) const
{
if (m_completed) {
if (!m_sortRoleName.isEmpty()) {
if (QSortFilterProxyModel::lessThan(source_left, source_right))
return m_ascendingSortOrder;
if (QSortFilterProxyModel::lessThan(source_right, source_left))
return !m_ascendingSortOrder;
}
for(auto sorter : m_sorters) {
if (sorter->enabled()) {
int comparison = sorter->compareRows(source_left, source_right);
if (comparison != 0)
return comparison < 0;
}
}
}
return source_left.row() < source_right.row();
}
void QQmlSortFilterProxyModel::resetInternalData()
{
QSortFilterProxyModel::resetInternalData();
if (sourceModel() && QSortFilterProxyModel::roleNames().isEmpty()) { // workaround for when a model has no roles and roles are added when the model is populated (ListModel)
// QTBUG-57971
connect(sourceModel(), &QAbstractItemModel::rowsInserted, this, &QQmlSortFilterProxyModel::initRoles);
connect(this, &QAbstractItemModel::rowsAboutToBeInserted, this, &QQmlSortFilterProxyModel::initRoles);
}
}
void QQmlSortFilterProxyModel::invalidateFilter()
{
if (m_completed)
QSortFilterProxyModel::invalidateFilter();
}
void QQmlSortFilterProxyModel::invalidate()
{
if (m_completed)
QSortFilterProxyModel::invalidate();
}
void QQmlSortFilterProxyModel::updateFilterRole()
{
QList<int> filterRoles = roleNames().keys(m_filterRoleName.toUtf8());
if (!filterRoles.empty())
{
setFilterRole(filterRoles.first());
}
}
void QQmlSortFilterProxyModel::updateSortRole()
{
QList<int> sortRoles = roleNames().keys(m_sortRoleName.toUtf8());
if (!sortRoles.empty())
{
setSortRole(sortRoles.first());
invalidate();
}
}
void QQmlSortFilterProxyModel::updateRoles()
{
updateFilterRole();
updateSortRole();
}
void QQmlSortFilterProxyModel::initRoles()
{
disconnect(sourceModel(), &QAbstractItemModel::rowsInserted, this, &QQmlSortFilterProxyModel::initRoles);
disconnect(this, &QAbstractItemModel::rowsAboutToBeInserted, this , &QQmlSortFilterProxyModel::initRoles);
resetInternalData();
updateRoles();
}
QVariantMap QQmlSortFilterProxyModel::modelDataMap(const QModelIndex& modelIndex) const
{
QVariantMap map;
QHash<int, QByteArray> roles = roleNames();
for (QHash<int, QByteArray>::const_iterator it = roles.begin(); it != roles.end(); ++it)
map.insert(it.value(), sourceModel()->data(modelIndex, it.key()));
return map;
}
void QQmlSortFilterProxyModel::append_filter(QQmlListProperty<Filter>* list, Filter* filter)
{
if (!filter)
return;
QQmlSortFilterProxyModel* that = static_cast<QQmlSortFilterProxyModel*>(list->object);
that->m_filters.append(filter);
connect(filter, &Filter::invalidate, that, &QQmlSortFilterProxyModel::invalidateFilter);
filter->m_proxyModel = that;
that->invalidateFilter();
}
int QQmlSortFilterProxyModel::count_filter(QQmlListProperty<Filter>* list)
{
QList<Filter*>* filters = static_cast<QList<Filter*>*>(list->data);
return filters->count();
}
Filter* QQmlSortFilterProxyModel::at_filter(QQmlListProperty<Filter>* list, int index)
{
QList<Filter*>* filters = static_cast<QList<Filter*>*>(list->data);
return filters->at(index);
}
void QQmlSortFilterProxyModel::clear_filters(QQmlListProperty<Filter> *list)
{
QQmlSortFilterProxyModel* that = static_cast<QQmlSortFilterProxyModel*>(list->object);
that->m_filters.clear();
that->invalidateFilter();
}
void QQmlSortFilterProxyModel::append_sorter(QQmlListProperty<Sorter>* list, Sorter* sorter)
{
if (!sorter)
return;
auto that = static_cast<QQmlSortFilterProxyModel*>(list->object);
that->m_sorters.append(sorter);
connect(sorter, &Sorter::invalidate, that, &QQmlSortFilterProxyModel::invalidate);
sorter->m_proxyModel = that;
that->invalidate();
}
int QQmlSortFilterProxyModel::count_sorter(QQmlListProperty<Sorter>* list)
{
auto sorters = static_cast<QList<Sorter*>*>(list->data);
return sorters->count();
}
Sorter* QQmlSortFilterProxyModel::at_sorter(QQmlListProperty<Sorter>* list, int index)
{
auto sorters = static_cast<QList<Sorter*>*>(list->data);
return sorters->at(index);
}
void QQmlSortFilterProxyModel::clear_sorters(QQmlListProperty<Sorter>* list)
{
auto that = static_cast<QQmlSortFilterProxyModel*>(list->object);
that->m_sorters.clear();
that->invalidate();
}
int QQmlSortFilterProxyModel::getRowCount() const
{
return rowCount();
}
void registerQQmlSortFilterProxyModelTypes() {
qmlRegisterType<QQmlSortFilterProxyModel>("SortFilterProxyModel", 0, 2, "SortFilterProxyModel");
}
Q_COREAPP_STARTUP_FUNCTION(registerQQmlSortFilterProxyModelTypes)
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));
}
}
I have
QListView *myListView;
QStringList *myStringList;
QStringListModel *myListModel;
which I fill with data like this:
myStringList->append(QString::fromStdString(...));
myListModel->setStringList(*myStringList);
myListView->setModel(myListModel);
I want to change the font-color of some list entries, so I tried:
for (int i = 0; i < myListModel->rowCount(); ++i) {
std::cerr << myListModel->index(i).data().toString().toStdString() << std::endl;
myListModel->setData(myListModel->index(i), QBrush(Qt::green), Qt::ForegroundRole);
}
The data is print out to cerr correctly, but the color does not change. What am I missing?
QStringListModel supports only Qt::DisplayRole and Qt::EditRole roles.
You have to reimplement the QStringListModel::data() and QStringListModel::setData() methods to support other roles.
Example:
class CMyListModel : public QStringListModel
{
public:
CMyListModel(QObject* parent = nullptr)
: QStringListModel(parent)
{}
QVariant data(const QModelIndex & index, int role) const override
{
if (role == Qt::ForegroundRole)
{
auto itr = m_rowColors.find(index.row());
if (itr != m_rowColors.end());
return itr->second;
}
return QStringListModel::data(index, role);
}
bool setData(const QModelIndex & index, const QVariant & value, int role) override
{
if (role == Qt::ForegroundRole)
{
m_rowColors[index.row()] = value.value<QColor>();
return true;
}
return QStringListModel::setData(index, value, role);
}
private:
std::map<int, QColor> m_rowColors;
};
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
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.