2013-09-28 78 views
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 

回答

19

您的示例過於簡化,因爲docs很清楚地聲明類/結構bei NG傳遞給Q_DECLARE_METATYPE必須有一個默認的構造函數,拷貝構造函數和一個公共析構函數:http://qt-project.org/doc/qt-5.0/qtcore/qmetatype.html#Q_DECLARE_METATYPE

話雖這麼說,這裏是一個非常簡單的例子,顯示Q_DECLARE_METATYPE工作:

#include <QMetaType> 
#include <QVariant> 
#include <QDebug> 

namespace MyNS { 
    class MyClass { 
    public: 
     MyClass() : value(0) { } 
     MyClass(int value) : value(value) { } 
     MyClass(const MyClass &other) { value = other.value; } 
     ~MyClass() { } 
     int getValue() const { return value; } 
    private: 
     int value; 
    }; 
}; 

Q_DECLARE_METATYPE(MyNS::MyClass); 

int main(int argc, char *argv[]) 
{ 
    MyNS::MyClass m(15); 
    QVariant v = QVariant::fromValue(m); 
    qDebug() << v.canConvert<MyNS::MyClass>(); 
    qDebug() << v.value<MyNS::MyClass>().getValue(); 
} 
+1

是的,我突然意識到,其中問題是。問題是,當實現MyModel :: data(const QModelIndex&index,int role)const時,我應該使用'return QVariant :: fromValue(MyClass)'而不是'return Myclass'。 – user2826776

+0

閱讀[Qt自定義類型文檔](http://doc.qt.io/qt-5/custom-types.html),我不確定如何使用宏。當'Q_DECLARE_METATYPE(MyClass);'在類本身的範圍內時,編譯失敗,並且在非命名空間範圍'class MyClass''中顯式異常。該示例顯示了插入宏的正確位置。謝謝! – fgiraldeau