Can __FILE__ and __LINE__ be made linkable when printed to Qt Creator's debug console?

北战南征 提交于 2020-01-12 14:41:48

问题


Header:

#define TRACE_ERROR(s)                      \
{
  ...
  char TraceBuffer[512];
  sprintf(TraceBuffer, "%s\t(%s:%d)", s, __FILE__, __LINE__);
  DebugErrTrace(TraceBuffer);
  ...
}

Implementation:

void DebugErrTrace(char *String, ...) {
  ...
  qDebug() << String;
}

The above spits out a line of debug trace, which might look something like

ERROR File Missing! (..\trunk\Common\FileManager.cpp:102)

in Qt Creator's debug console.

I've noticed that Qt's own error messages e.g.

Object::connect: No such slot cClass::Method(QString) in ..\trunk\Components\Class.cpp:301

create what looks like a hyperlink around the __FILE__:__LINE__ part of the debug line, linking to the line which caused the problem. Is there any way I can I do this with my own debug output?

Cheers, Sam


回答1:


According to Qt Creator source code (there), the hyperlinks are only created for lines matching these regular expressions:

"^(?:\\[Qt Message\\] )?(file:///.+:\\d+(?::\\d+)?):"
"Object::.*in (.*:\\d+)"
"ASSERT: .* in file (.+, line \\d+)"
"^   Loc: \\[(.*)\\]"

So the simplest lines you could construct look like this:

qWarning("file:///%s:%i: %s", __FILE__, __LINE__, "your message");
qWarning("   Loc: [%s:%i] %s", __FILE__, __LINE__, "your message");

Qt Creator doesn't seem to care if the path after "file:///" is absolute or not.




回答2:


In addition to alexisdm's answer (which helped me very much, big thanks!):

Instead of defining a custom macro, I would suggest to do the following in newer versions of Qt and use qDebug itself:

qSetMessagePattern("%{if-category}%{category}: %{endif}%{message}\n   Loc: [%{file}:%{line}]");

The part before \n is Qt's default message pattern, and splitting with \n has the benefit that the log messages also can contain characters like [ or ] without messing up the links.

The message pattern can easily be extended with other log details like timestamps, thread id and so on, see the documentation. When adding other details, keep the link in a seperate line to avoid issues with Qt Creator's parsing.



来源:https://stackoverflow.com/questions/7916267/can-file-and-line-be-made-linkable-when-printed-to-qt-creators-debug-co

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!