自定义一个QEvent应该很简单:
class CustomEvent : public QEvent
{
public:
CustomEvent() : QEvent(static_cast<Type>(User+1))
{
}
};
不过传给父类的Type参数似乎有点让人头痛,因为用该事件的时候,一般都还要使用这个Type的值。
static成员变量
让Type作为该类的静态成员,应该是我们比较期待的:
class CustomEvent : public QEvent
{
public:
static const Type myType = static_cast<Type>(User+1);
CustomEvent() : QEvent(myType)
{
}
};
这样一来,使用(处理)事件时
if (event->type()==CustomEvent::myType)
{
}
不过呢,直接使用QEvent::User+1 这种东西,无法避免Type的重复。恩,要解决问题,需要使用:
registerEventType
int QEvent::registerEventType ( int hint = -1 )
这样一来,代码变成:
//x.h
class CustomEvent : public QEvent
{
public:
static const Type myType;
CustomEvent() : QEvent(myType)
{
}
};
//x.cpp
const QEvent::Type CustomEvent::myType = static_cast<QEvent::Type>(QEvent::registerEventType());
函数调用不能在类定义中初始化常量,只能放.cpp 文件中了。
static 成员函数
除了静态的成员变量,我们还可以使用静态的成员函数
class CustomEvent : public QEvent
{
public:
static Type registeredType()
{
static Type myType = static_cast<Type>(registerEventType());
return myType;
}
CustomEvent() : QEvent(registeredType())
{
}
};
多个Type?
如果我的CustomEvent接受 Type 参数,又该如何是好?
class CustomEvent : public QEvent
{
public:
CustomEvent(Type t) : QEvent(t)
{
}
};
恩,还是用一堆 static 的静态数据成员吧,大概类似于
// x. h
class CustomEvent : public QEvent
{
public:
static Type myType1;
static Type myType2;
static Type myType3;
CustomEvent(Type t) : QEvent(t)
{
}
};
//x.cpp
QEvent::Type CustomEvent::myType1 = static_cast<QEvent::Type>(QEvent::registerEventType());
QEvent::Type CustomEvent::myType2 = static_cast<QEvent::Type>(QEvent::registerEventType());
QEvent::Type CustomEvent::myType3 = static_cast<QEvent::Type>(QEvent::registerEventType());
参考
http://stackoverflow.com/questions/2248009/qt-defining-a-custom-event-type
http://stackoverflow.com/questions/2495254/qt-send-signal-to-main-application-window
http://lists.qt.nokia.com/pipermail/qt-interest/2010-December/029853.html

927

被折叠的 条评论
为什么被折叠?



