Mohammad Kanan
Mohammad Kanan

Reputation: 4582

How to know which QObject::connect is failing

I have an application with tens of signal slot connections, in particular multiple classes (with decomposition) are implementing almost identical QObject::connect signals to slots, the problem I am facing is sometimes, in QtCreator Application Output, I get the usual error:

QObject::connect: Cannot connect (null)::SessionClosed() to mainWindow_Desktop::stop_Scanning()

But it lacks any indication from which file/line or code segment the error is coming from and the expense of that is I have to check all similar connections to detect which one went in error! my question is: Is there any way to directly know the file/line the error refers to?

Upvotes: 2

Views: 1894

Answers (2)

Ruslan
Ruslan

Reputation: 19120

Set breakpoints on QMessageLogger::warning, QMessageLogger::critical etc.. Then you'll have your application stopped on such messages by qWarning, qCritical etc. from Qt, and call stack will tell you where they originate.

Example code:

#include <QObject>

void f()
{
    QObject::connect(0,"kkk",0,"aaa");
}

int main()
{
    f();
}

After compiling, when I run it with GDB, I get:

$ gdb -ex 'set breakpoint pending on' -ex 'b QMessageLogger::warning' \
      -ex r -ex bt ./test
Reading symbols from ./test...done.
Function "QMessageLogger::warning" not defined.
Breakpoint 1 (QMessageLogger::warning) pending.
Starting program: /tmp/test/test 
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1".

Breakpoint 1, QMessageLogger::warning (this=this@entry=0x7fffffffd2e0, msg=msg@entry=0x7ffff7c3ac80 "QObject::connect: Cannot connect %s::%s to %s::%s") at global/qlogging.cpp:541
541     {
#0  QMessageLogger::warning (this=this@entry=0x7fffffffd2e0, msg=msg@entry=0x7ffff7c3ac80 "QObject::connect: Cannot connect %s::%s to %s::%s") at global/qlogging.cpp:541
#1  0x00007ffff7b64a4d in QObject::connect (sender=0x0, signal=0x400838 "kkk", receiver=<optimized out>, method=<optimized out>, type=<optimized out>) at kernel/qobject.cpp:2618
#2  0x0000000000400788 in f () at test.cpp:5
#3  0x00000000004007a0 in main () at test.cpp:10

Here we can see that the bad call to connect occurs in test.cpp:5 in f().

Upvotes: 2

dtech
dtech

Reputation: 49289

QMetaObject::Connection QObject::connect() has a return value, which comes with an implicit bool conversion operator, so you can simply test whether it succeeded with an if statement and if necessary issue a warning that can tell you where it happens if verbose warnings are enabled.

Naturally you can manually use the __FILE__, __LINE__ and __FUNCTION__ macros yourself.

Upvotes: 3

Related Questions