Is it possible to emit a Qt signal from a const method?

DataGraham picture DataGraham · Apr 25, 2011 · Viewed 8.9k times · Source

In particular, I am implementing a QWizardPage ("MyWizardPage") for a QWizard, and I want to emit a signal ("sigLog") from my override of the QWizardPage::nextId virtual method.

Like so:

class MyWizardPage
    : public QWizardPage
{
    Q_OBJECT
public:
    MyWizardPage();
    virtual int nextId() const;
Q_SIGNALS:
    void sigLog(QString text);
};

int MyWizardPage::nextId() const
{
    Q_EMIT sigLog("Something interesting happened");
}

But when I try this, I get the following compile error on the Q_EMIT line:

Error 1 error C2662: 'MyWizardPage::sigLog' : cannot convert 'this' pointer from 'const MyWizardPage' to 'MyWizardPage &'

Answer

DataGraham picture DataGraham · Apr 26, 2011

It is possible to emit a signal from a const method by adding "const" to the signal declaration, like so:

void sigLog(QString text) const;

I tested this and it does compile and run, even though you don't actually implement the signal as a normal method yourself (i.e. Qt is okay with it).