Stan
Stan

Reputation: 38255

Debugging mode for Qt GUI application

I would like to add a debugging mode for Qt GUI application. In debugging mode, any GUI widget events would dump out debug information rather than doing the original functionality. For example, clicking button A would print out the checkbox options being selected, where button A's original function is process something to the selected options.

I was thinking to add a menu option "debug mode", or a secret keyboard shortcut to enable it. And in the callback functions associated with widget signals (clicked/ textEdited), use if(isDebugMode)/else to distinguish regular function mode code.

Is this a good model to test GUI functionality? Is there any better way?

Upvotes: 0

Views: 1713

Answers (1)

ypnos
ypnos

Reputation: 52327

You might want to use the Signal/Slot system for your debugging. It reminds me of aspect-oriented programming.

  1. Write a Debug class derived from QObject that holds several slots with the typical signatures.
  2. In these slots, use the QObject::sender() function to retrieve the originator of the event
  3. Connect all signals to the debug slots additionally to their original receivers. Do this in code blocks that are run on condition of your debug mode flag.
  4. Connect additional signals from the Qt objects to allow you follow the state of the application. E.g. if a button reads a checkbox option, also connect the change signals from the checkboxes to your debug slots so you can read their state from previous output when the button is clicked.
  5. (If you don't want original action to be performed, simply make the connection of signals equally conditioned on the debug flag, this time in reverse.)

This will help you in keeping most of your code clean of the debug stuff.

For an inspiration, here is some example code that tracks focus changes within the application:

debug.hpp

class Debug : public QObject
{
    Q_OBJECT
    ...
    // method for debugging focus
    void focusChange(QWidget * old, QWidget * now);
};

debug.cpp

void Debug::focusChange(QWidget *old, QWidget *now)
{
    if (!old || !now)
        return;
    std::cerr << "Focus changed from " << old->objectName().toStdString()
              << " to " << now->objectName().toStdString() << std::endl;
}

main.cpp

QApplication app(argc, argv);
Debug dbg;
...
app.connect(&app, SIGNAL(focusChanged(QWidget*, QWidget*)),
            &debug, SLOT(focusChange(QWidget*, QWidget*)));
// run Qt event loop
return app.exec();

Upvotes: 1

Related Questions