Originally Posted by
d_stranz
Why can't he add a cast operator to his MyStruct class?
Because he wants to convert to QString from QVariant and not his own class.
Wouldn't that end up getting invoked by QVariant:toString()?
No. QVariant::toString() calls QVariant::canConvert<QString>() and that returns false for custom types.
He might have to declare his variant as a "String" type
This is not possible, each type gets its own meta type id.
Originally Posted by
zickedi
My intention was to build a model like QStringListModel and save information how often an item is added. This additional information should not be in the model but in the registered type (MyStruct).
Pseudocode:
bool setData(...);
QVariantList lst;
};
int main() {
MyStruct struct;
struct.name = "Test";
struct.counter += 1;
QVariantListModel model = new QVariantListModel();
return 0;
}
class QVariantListModel : QAbstractListModel {
bool setData(...);
QVariantList lst;
};
int main() {
MyStruct struct;
struct.name = "Test";
struct.counter += 1;
QVariantListModel model = new QVariantListModel();
model->setData(QModelIndex(), QVariant::fromValue(struct)); // Add data to model.
return 0;
}
To copy to clipboard, switch view to plain text mode
Possible internal list should look like this:
lst = { ["entry1",2], ["entry2", 5] }
I think you are approaching the problem from the wrong side. I think you want something like this (not tested):
public:
int rowCount
(const QModelIndex &parent
= QModelIndex()) const { return parent.
isValid() ?
0 : m_data.
count();
} if(index.
row() <
0 || index.
row() >
= m_data.
count()) return QVariant();
const MyStruct &item = m_data.at(index.row());
const int c = index.column();
switch(role) {
case Qt::DisplayRole:
case Qt::EditRole:
if(c==0) return item.name;
if(c==1) return item.count;
break;
}
}
// follow with insertRows(), removeRows() and setData() implementations to make the model read-write
private:
QList<MyStruct> m_data;
};
class MyModel : public QAbstractTableModel {
public:
MyModel(QObject *parent = 0) : QAbstractListModel(parent) {}
int rowCount(const QModelIndex &parent = QModelIndex()) const { return parent.isValid() ? 0 : m_data.count(); }
int columnCount(const QModelIndex &parent = QModelIndex()) const { return parent.isValid() ? 0 : 2; }
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const {
if(index.row() < 0 || index.row() >= m_data.count()) return QVariant();
const MyStruct &item = m_data.at(index.row());
const int c = index.column();
switch(role) {
case Qt::DisplayRole:
case Qt::EditRole:
if(c==0) return item.name;
if(c==1) return item.count;
break;
}
return QVariant();
}
// follow with insertRows(), removeRows() and setData() implementations to make the model read-write
private:
QList<MyStruct> m_data;
};
To copy to clipboard, switch view to plain text mode
Bookmarks