Setting custom data for the QStringListModel item

核能气质少年 提交于 2020-01-02 05:28:29

问题


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.


回答1:


Try using a QStandardItemModel instead of QStringListModel.

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



来源:https://stackoverflow.com/questions/9991056/setting-custom-data-for-the-qstringlistmodel-item

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!