11
我想在QAbstractListModel中使用自定义类,而Q_DECLARE_METATYPE根本不起作用!Q_DECLARE_METATYPE根本不起作用
要测试问题出在哪里,我已经简化了代码如下:
#include <QMetaType>
#include <QVariant>
#include <QDebug>
typedef int x;
Q_DECLARE_METATYPE(x)
void main() {
QVariant v;
qDebug() << v.canConvert<x>();
}
,输出仍然是假的!
顺便说一句,我想要实现的代码是这样的:
namespace ns{
class a {
public:
a(); //default constructor
a(const a&); //copy constructor
~a();
}
}
Q_DECALRE_METATYPE(ns::a);
,当我尝试重新实现这样QAbstractListModel ::数据:
QList<ns::s> list; //this is actually a member field of the custom model.
QVariant MyListModel::data(const QModelIndex& index, int role) const {
Q_UNUSED(role)
return list.at(index.row());
}
编译器将报告和错误,如:
cannot convert const ns::a to QVariant::Type
是的,我突然意识到,其中问题是。问题是,当实现MyModel :: data(const QModelIndex&index,int role)const时,我应该使用'return QVariant :: fromValue(MyClass)'而不是'return Myclass'。 – user2826776
阅读[Qt自定义类型文档](http://doc.qt.io/qt-5/custom-types.html),我不确定如何使用宏。当'Q_DECLARE_METATYPE(MyClass);'在类本身的范围内时,编译失败,并且在非命名空间范围'class MyClass''中显式异常。该示例显示了插入宏的正确位置。谢谢! – fgiraldeau