如何从QEvent获取人类可读的事件类型? [英] How to get human-readable event type from QEvent?

查看:156
本文介绍了如何从QEvent获取人类可读的事件类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想调试事件处理代码,并想将QEvent::Type枚举的值转换为人类可读的字符串. QEvent有一个Q_GADGET宏,所以大概有一种方法可以实现?

I want to debug event handling code and would like to convert QEvent::Type enum's value to a human-readable string. QEvent has a Q_GADGET macro, so presumably there's a way of pulling that off?

推荐答案

在将事件输出到调试流时,最新版本的Qt做正确的事,因此以下内容不是必需的.出现类似于warning C4273: 'operator <<' : inconsistent dll linkage的错误,这意味着您的Qt版本已经支持此功能,而无需下面的代码.

Recent versions of Qt do the right thing when outputting events to the debug stream, so the below isn't neccessary. If you get an error similar to warning C4273: 'operator <<' : inconsistent dll linkage, it means that your version of Qt already supports this without need for the code below.

Q_GADGET宏将QMetaObject staticMetaObject成员添加到类中.静态元对象的定义是由moc生成的,在QEvent的情况下,它包含枚举信息.

The Q_GADGET macro adds a QMetaObject staticMetaObject member to the class. The static metaobject's definition is generated by moc, and it - in the case of QEvent - contains the enumeration information.

下面是一个示例,说明了如何利用它来提供更合理的QDebug事件输出.

Below is an example of how to leverage that to give a more reasonable QDebug output of events.

#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;
}

这篇关于如何从QEvent获取人类可读的事件类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆