Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it OK to emit a signal from an object's destructor in Qt?

Tags:

c++

qt

When a QObject-derived object is being destructed, is it OK to emit a signal from its destructor? I tried it and it seems to work, but I'm not sure if it should be done.

For example, this code

class MyClass : public QObject {
signals:
    void mySignal(const QString &str);
public:
    QString myString;
    ~MyClass() { emit mySignal(myString); }
}

would pass a const reference to an object that might be out of scope by the time when the connected slot is executed.

like image 442
sashoalm Avatar asked Dec 24 '12 19:12

sashoalm


People also ask

How do you emit a signal in Qt?

In Qt, we have an alternative to the callback technique: We use signals and slots. A signal is emitted when a particular event occurs. Qt's widgets have many predefined signals, but we can always subclass widgets to add our own signals to them. A slot is a function that is called in response to a particular signal.

Can we connect signal to signal in Qt?

This ensures that truly independent components can be created with Qt. You can connect as many signals as you want to a single slot, and a signal can be connected to as many slots as you need. It is even possible to connect a signal directly to another signal.

How do you block signals in Qt?

If you just don't want the signal to be emitted at one specific time, you can use QObject::blockSignals like this: bool oldState = checkBox->blockSignals(true); checkBox->setChecked(true); checkBox->blockSignals(oldState); The downside of this approach is that all signals will be blocked.


1 Answers

Emission is generally fine (QObject does it too with the "destroyed" signal), including a case as yours. When the connection is direct, the string is still alive. And when it is QueuedConnection, then the string is first copied to the event loop.

like image 155
Johannes Schaub - litb Avatar answered Sep 29 '22 03:09

Johannes Schaub - litb