variant 中的困惑

QVariant v = qVariantFromValue((void *) a);
a = (A *) v.value<void *>();

Q_DECLARE_METATYPE ( Type )
This macro makes the type Type known to QMetaType. It is needed to use the type Type as a custom type in QVariant.
Ideally, this macro should be placed below the declaration of the class or struct. If that is not possible, it can be put in a private header file which has to be included every time that type is used in a QVariant.
Adding a Q_DECLARE_METATYPE() makes the type known to all template based functions, including QVariant. Note that if you intend to use the type in queued signal and slot connections, you also have to call qRegisterMetaType() since such connections are resolved at runtime.
This example shows a typical use case of Q_DECLARE_METATYPE():

struct MyStruct
{
int i;
...
};

Q_DECLARE_METATYPE(MyStruct)
If MyStruct is in a namespace, the Q_DECLARE_METATYPE() macro has to be outside the namespace:

namespace MyNamespace
{
...
}

Q_DECLARE_METATYPE(MyNamespace::MyStruct)

Since MyStruct is now known to QMetaType, it can be used in QVariant:

MyStruct s;
QVariant var;
var.setValue(s); // copy s into the variant

...

// retrieve the value
MyStruct s2 = var.value<MyStruct>();
以上的方法果然好用,在沒有使用Q_DECLARE_METATYPE(QPushButton *)的時候
QVariant data = qVariantFromValue<QPushButton *>(temp);
報錯誤:
error: ‘qt_metatype_id’ is not a member of ‘QMetaTypeId<QPushButton*>’
但是使用了以後就沒有了這個錯誤,類型還真的是要註冊的。

Q_DECLARE_METATYPE(QPushButton *)

QPushButton *temp = new QPushButton;
temp->setText(QObject::tr("haha"));
QVariant data = qVariantFromValue<QPushButton *>(temp);
QPushButton *get = data.value<QPushButton *>();
qDebug() << get->text();
上面是測試代碼,恩


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章