I'm trying to implement my own model/delegate where the model returns pointers to a QHash<QString, QString> *. I've called Q_DECLARE_METATYPE in order to register the new type and have also called qRegisterMetaType<MyType>("MyType"). Unfortunately, when I try to convert the call to index.data(Qt:
isplayType) into <QHash<QString, QString> *, all I seem to get back is a null pointer...
typedef QHash<QString, QString>* MyType;
Q_DECLARE_METATYPE(MyType)
{
Q_OBJECT
public:
};
typedef QHash<QString, QString>* MyType;
Q_DECLARE_METATYPE(MyType)
class MyDelegate : public QItemDelegate
{
Q_OBJECT
public:
MyDelegate(QWidget *parent = 0);
virtual void paint(QPainter *painter, const QStyleOptionViewItem &option,
const QModelIndex &index) const;
};
To copy to clipboard, switch view to plain text mode
So the declaration above helped me get the code to compile.
MyDelegate
::MyDelegate(QWidget *parent
){
qRegisterMetaType<MyType>("MyType");
}
{
QRect rect
= option.
rect;
QHash<QString, QString> * t = 0;
t = qVariantValue<QHash<QString, QString>*>(index.data(Qt::DisplayRole));
if(t != 0)
{
std::cout << "T size: " << t->size() << std::endl;
}
if(option.
state & QStyle::State_Selected) {
painter->fillRect(rect, option.palette.highlight());
}
else
{
}
}
MyDelegate::MyDelegate(QWidget *parent)
:QItemDelegate(parent)
{
qRegisterMetaType<MyType>("MyType");
}
void MyDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option,
const QModelIndex &index) const
{
QRect rect = option.rect;
QHash<QString, QString> * t = 0;
t = qVariantValue<QHash<QString, QString>*>(index.data(Qt::DisplayRole));
if(t != 0)
{
std::cout << "T size: " << t->size() << std::endl;
}
if(option.state & QStyle::State_Selected)
{
painter->fillRect(rect, option.palette.highlight());
}
else
{
QItemDelegate::paint(painter, option, index);
}
}
To copy to clipboard, switch view to plain text mode
Now something is going wrong on lines 12 and 13. Perhaps something about my data declaration below is incorrect? Of course I'm expecting that I should now have a handle on that index in the model. If I did, then I would proceed to format everything in the paint call.
{
if(!index.isValid())
{
}
if(role == Qt::TextAlignmentRole)
{
return int(Qt::AlignRight | Qt::AlignVCenter);
}
else if (role == Qt::DisplayRole)
{
//Returning a pointer to the QHash<QString, QString> so just
//cast back and then use the data in the view.
return tableData.at(index.row());
}
}
QVariant CustomModel::data(const QModelIndex &index, int role)const
{
if(!index.isValid())
{
return QVariant();
}
if(role == Qt::TextAlignmentRole)
{
return int(Qt::AlignRight | Qt::AlignVCenter);
}
else if (role == Qt::DisplayRole)
{
//Returning a pointer to the QHash<QString, QString> so just
//cast back and then use the data in the view.
return tableData.at(index.row());
}
return QVariant();
}
To copy to clipboard, switch view to plain text mode
Thanks for taking your time
Bookmarks