我想调试事件处理代码,并希望将QEvent::Type
枚举值转换为人类可读的字符串。 QEvent
有一个Q_GADGET
宏,所以可能有一种方法可以解决这个问题吗?
答案 0 :(得分:23)
Qt的最新版本在将事件输出到调试流时做了正确的事情,因此下面不是必需的。如果您收到类似于warning C4273: 'operator <<' : inconsistent dll linkage
的错误,则表示您的Qt版本已经支持此版本而无需下面的代码。
Q_GADGET
宏会向该类添加QMetaObject staticMetaObject
成员。静态元对象的定义由moc生成,而在QEvent
的情况下,它包含枚举信息。
以下是如何利用它来提供更合理的QDebug
事件输出的示例。
#include <QEvent>
#include <QMetaEnum>
#include <QDebug>
/// Gives human-readable event type information.
QDebug operator<<(QDebug str, const QEvent * ev) {
static int eventEnumIndex = QEvent::staticMetaObject
.indexOfEnumerator("Type");
str << "QEvent";
if (ev) {
QString name = QEvent::staticMetaObject
.enumerator(eventEnumIndex).valueToKey(ev->type());
if (!name.isEmpty()) str << name; else str << ev->type();
} else {
str << (void*)ev;
}
return str.maybeSpace();
}
使用示例:
void MyObject::event(QEvent* ev) {
qDebug() << "handling an event" << ev;
}
答案 1 :(得分:3)
可以组合Q_GADGET和Q_ENUM以获取以下模板:
template<typename EnumType>
QString ToString(const EnumType& enumValue)
{
const char* enumName = qt_getEnumName(enumValue);
const QMetaObject* metaObject = qt_getEnumMetaObject(enumValue);
if (metaObject)
{
const int enumIndex = metaObject->indexOfEnumerator(enumName);
return QString("%1::%2::%3").arg(metaObject->className(), enumName, metaObject->enumerator(enumIndex).valueToKey(enumValue));
}
return QString("%1::%2").arg(enumName).arg(static_cast<int>(enumValue));
}
示例:
void MyObject::event(QEvent* ev)
{
qDebug() << ToString(ev->type());
}