Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting custom data for the QStringListModel item

I have QStringListModel

QStringListModel* blocksModel = new QStringListModel();

And a class inherited from the QObject

class Block : public QObject
{
    Q_OBJECT

public:

    Block();
    Block(const Block& other);
    ~Block;

//and other stuff here    

};
Q_DECLARE_METATYPE(Block*)

When I set a data for the Qt::EditRole, everything works fine but when I'm trying to set data for the Qt::UserRole, it never returns true, and when I'm getting data I see invalid QVariant

int count = blocksModel->rowCount();
blocksModel->insertRows(count, 1);
QModelIndex index = blocksModel->index(count, 0);

// it works
QString name = QString("Block %1").arg(count + 1);
blocksModel->setData(index, name);

QVariant var = QVariant::fromValue(block);
// it doesn`t work
bool setSuccessful = blocksModel->setData(index, var, Qt::UserRole);

//invalid QVariant
QVariant var2 = index.data(Qt::UserRole);
Block* oneMoreBlock = var2.value<Block*>();

In fact no matter wich type of data I'm trying to set for the item, this also doesn`t work:

blocksModel->setData(index, QVariant(1), Qt::UserRole);

And I`ve tried Qt::UserRole + 1, and got the same result. Maybe I should define ItemDataRoles used by the model somehow?

Any ideas? Thanks.

like image 395
alpex Avatar asked Apr 03 '12 10:04

alpex


1 Answers

Try using a QStandardItemModel instead of QStringListModel.

QStringListModel doesn't seem to support Qt::UserRole.

like image 82
Jokahero Avatar answered Oct 15 '22 19:10

Jokahero