Debugging Qt's signal-slot connections

What do you do if you think that you've correctly connected a signal to a slot and yet your slot's not being fired?

Here's a bunch of things you can try:

  • Check the compile log for error messages about undefined signals and slots.
  • Check the runtime log for errors on connection. If need be, ensure that the connection succeeds by testing its return value (it should return true).
  • Check to make sure that the connect code, the emit code, and the slot code is reached. (Odds are one of them isn't.)
  • Make sure that you declare the connection as follows:
    connect(sender, SIGNAL(someSignal(type)), receiver,     
            SLOT(received(type)))
  • The signal and slot specifications should have the argument types, but not the arguments themselves. Moreover, you can omit const and the reference specifications in the arguments; the metaobject compiler strips them anyway.
  • Check the parameters of the signal and slot and ensure that they match precisely.
  • Check to be sure that you've correctly declared the signal and slot portions of your header correctly.
  • For that matter, be sure that your sender and receiver both inherit from QObject and that you have Q_OBJECT declared in your class definition. Remember, you need to do both.
  • If you've forgotten part of the QObject declaration in your header, rerun qmake and rebuild.
  • Make sure that you make the connection with connect before you invoke any functions that fire the signal.
  • Make sure that you're not disconnecting the signal anywhere with disconnect.

Usually, the problem is pretty easy to track down, especially if you check the log and the signal and slot declarations closely. A common mistake is to wire a signal to a slot that's not been declared a slot, so check your headers closely!

Another thing to note: are your signals not disconnecting when they should? Consider the following line:

disconnect(object);

The preceding line is not the same as the following:

disconnect(object, 0, 0, 0);

This makes perfect sense when you look at the overloaded function definitions for disconnect, which read:

bool QObject::disconnect ( const QObject * receiver, const char * method = 0 ).

Calling disconnect and passing only an object disconnects all the signals, rather than just the signal that you choose.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset