c++qtqt-creator

Create a flag for a Qt project or use QLoggingCategory


This is my first question on this website, I hope I'll do it just fine.

I'm doing a Qt Project at work using a lot of signals and slots and I would like to create a flag/macro/variable to activate/deactivate the use of std::cout to trace which signal is emitted and which slot is activated.

This is for debugging purpose, to know how the different components of the application exchange and avoid loops in signals/slots.

More specifically, I would have a flag/variable in my .pro:

QT_SIGNALS_SLOTS_LOG = true

and in my source code:

if(QT_SIGNALS_SLOTS_LOG)
     std::cout << "MyClass::slotMySlot activated" << std::endl;

Questions:

1. Can I do something like that (using a variable of the .pro in the code)?

2. Is there a better way of doing that?


UPDATE 1

Burich, this works just fine, thanks

Now I will try to code a Qt macro which I put in my slots and which does all the work

Example:

Q_SIGNALS_SLOTS_LOG();

which gets the names of the Class and the Slot and do the

ifdef QT_SIGNALS_SLOTS_LOG
     std::cout << "MyClass::slotMySlot activated" << std::endl;
endif

Is there a way of doing that?


UPDATE 2

I used QLoggingCategory Class with this tutorial

I have a Class in my Utils folder with this code

#ifndef SIGNALSLOTDEBUG_H
#define SIGNALSLOTDEBUG_H
#include<QLoggingCategory>


Q_DECLARE_LOGGING_CATEGORY(logSignal)
Q_DECLARE_LOGGING_CATEGORY(logSlot)

inline static void debugSlotF( char const * caller_name )
{
    qCDebug(logSlot) << __TIME__ << caller_name << "activated";
}

inline static void debugSlot(){

}

#define debugSlot() debugSlotF(__PRETTY_FUNCTION__)

#endif // SIGNALSLOTDEBUG_H

In my code I just call

void HorizontalPatternListScene::slotSelectionChanged(int i)
{
    debugSlot();
    ....

I get this output:

log.slot: 12:06:54 void HorizontalPatternListScene::slotSelectionChanged(int) activated

And I can disable the stream by doing

QLoggingCategory::setFilterRules(
            "log.slot=true\n"
            "log.signal=false");

in my main.cpp


Solution

  • Set variable in pro:

    DEFINES += QT_SIGNALS_SLOTS_LOG
    

    Test it in code:

    #ifdef QT_SIGNALS_SLOTS_LOG
         std::cout << "MyClass::slotMySlot activated" << std::endl;
    #endif