我有一个通过拖放实现QAbstractListModel
来显示一个:QJsonArray
class NoteListModel : public QAbstractListModel
{
Q_OBJECT
public:
explicit NoteListModel(QObject *parent = nullptr);
~NoteListModel() override;
int rowCount(const QModelIndex &parent = QModelIndex()) const override;
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;
Qt::ItemFlags flags(const QModelIndex& index) const override;
// Drag & Drop:
bool canDropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent) const override;
bool dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent) override;
QStringList mimeTypes() const override {
QStringList mimes = QAbstractListModel::mimeTypes();
mimes.prepend("application/flynote_json");
return mimes;
}
QMimeData *mimeData(const QModelIndexList &indexes) const override;
Qt::DropActions supportedDropActions() const override;
private:
QJsonArray noteArray;
};
当我在我的mimeData()
方法中调用基本实现时,出现此错误:
QVariant::save: 无法保存类型 'QJsonValue' (type id: 45)
ASSERT failure in QVariant::save: "Invalid type to save"
QMimeData *NoteListModel::mimeData(const QModelIndexList &indexes) const
{
QMimeData *ret = nullptr;
if (indexes.size() == 1){
QModelIndex mi = indexes.first();
if (mi.isValid()){
ret = QAbstractListModel::mimeData(indexes);
QJsonDocument json_mime(noteArray.at(mi.row()).toObject());
ret->setData("application/flynote_json", json_mime.toJson());
}
}
return ret;
}
所以没问题,就像在文档中描述的那样,我添加了这些行:
// In the header (outside the class)
Q_DECLARE_METATYPE(QJsonValue)
QDataStream &operator<<(QDataStream &out, const QJsonValue &myObj){ /*...*/ }
QDataStream &operator>>(QDataStream &in, QJsonValue &myObj){ /*...*/ }
// In the constructor
qRegisterMetaType<QJsonValue>("QJsonValue");
qRegisterMetaTypeStreamOperators<QJsonValue>("QJsonValue");
但我有同样的问题,我做错了什么?