本文介绍了设置QStringListModel项的自定义数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有QStringListModel

I have QStringListModel

QStringListModel* blocksModel = new QStringListModel();

和从QObject继承的类

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*)



当我为Qt :: EditRole设置数据时,一切正常,但是当我试图设置Qt :: UserRole的数据,它从不返回true,当我得到数据我看到无效的QVariant

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*>();

事实上,无论我试图为该项设置什么类型的数据, `t work:

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);

我试过Qt :: UserRole + 1,得到相同的结果。也许我应该定义ItemDataRoles使用的模型以某种方式?

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

任何想法?感谢。

推荐答案

尝试使用QStandardItemModel而不是QStringListModel。

Try using a QStandardItemModel instead of QStringListModel.

QStringListModel似乎不支持Qt :: UserRole。

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

这篇关于设置QStringListModel项的自定义数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-27 13:10