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