PDA

View Full Version : subclassed const function problem



qtneuling
20th June 2008, 13:19
Hi,

i subclassed a QAbstractModel and subclassed the data function
which is declared as const.
However, i need to emit a signal from there and the compiler wont let me do that because of const...
What should i do?

mcosta
20th June 2008, 16:40
Simply you can't emit a signal inside a const method.

This is because a signal is transformed by moc into a call to QMetaObject::activate() with "this" as "sender" argument



void MyClass::mySignal()
{
QMetaObject::activate(this, &staticMetaObject, 0, 0);
}


This method declare the first argument as "QObject* sender" and then it can't be const

qtneuling
20th June 2008, 21:10
yes i know thats what the compiler tells me.
But i NEED this signal, what should i do? create another object on which i then can call the signal from the method?

Holy Cheater
21st June 2008, 18:46
redeclare it as a non-const in sub-class?

qtneuling
21st June 2008, 20:28
so how do i do that? just deleting "const" gives me errors related to qt.

marcel
21st June 2008, 20:45
of course it does... inheritance doesn't work that way.
what are you trying to do? there must be another way to do it.

Holy Cheater
21st June 2008, 22:04
class CBase : public QObject
{
Q_OBJECT
public:
CBase() : QObject(0) { someProtectedData = "something here"; };
QString someConstFunction() const { return someProtectedData; };
protected:
QString someProtectedData;
};

class CDerived : public CBase
{
Q_OBJECT
public:
QString someConstFunction() { emit someSignal(); someProtectedData = "changed"; return someProtectedData; };
signals:
void someSignal();
};

Constness removed in derived class. Isn't that which you are trying to do?
Another way is const_cast on "this".
Code above compiles without errors for me. Am I wrong somewhere?

qtneuling, probably you're trying to do something different.

marcel
21st June 2008, 22:07
Yes, but QAbstractItemModel::data is pure virtual.

qtneuling
22nd June 2008, 02:52
i need to emit this signal because my application needs to know when an item from my model was requested and which item it was

i created a new object with a method which emits the signal, and call that from the const function. This sucks but i dont see another way.