Answer the question
In order to leave comments, you need to log in
How to properly typecast in C++\Qt?
There is such a simple header:
#define PQ_OBJECT \
public:\
QStringList myList;
class PQWidget;
class PQWidget : public QWidget {
Q_OBJECT
PQ_OBJECT
public:
Q_INVOKABLE explicit PQWidget(QWidget *parent = 0)
: QWidget(parent){}
virtual ~PQWidget(){}
};
class PQPushButton;
class PQPushButton : public QPushButton {
Q_OBJECT
PQ_OBJECT
public:
Q_INVOKABLE explicit PQPushButton(QWidget *parent = 0)
: QPushButton(parent) {
myList << "text1";
myList << "text2";
}
};
// QObject -> PQWidget
QObject *button = new PQPushButton;
PQWidget *pbutton = (PQWidget*) button;
if(pbutton->myList.contains("text1")) {
qDebug() << "Okay!";
}
qDebug() << "QObject -> PQWidget OK!";
class PQObject;
class PQObject : public QObject {
Q_OBJECT
PQ_OBJECT
public:
Q_INVOKABLE explicit PQObject(QObject *parent = 0)
: QObject(parent){}
virtual ~PQObject(){}
};
class PQTimer;
class PQTimer : public QTimer {
Q_OBJECT
PQ_OBJECT
public:
Q_INVOKABLE explicit PQTimer(QObject *parent = 0)
: QTimer(parent) {
myList << "text1";
myList << "text2";
}
};
// QObject -> PQObject
QObject *timer = new PQTimer;
PQObject *ptimer = (PQObject*) timer;
if(ptimer->myList.contains("qwerty")) { // Segmentation fault
qDebug() << "Okay!";
}
qDebug() << "QObject -> PQObject OK!";
Answer the question
In order to leave comments, you need to log in
qmake can't build moc correctly most likely.
Try an explicit cast
QObject * myObj = qobject_cast(PQTimer);
In general, such a cast is a legacy of C, and in C ++ it is bad manners.
If you replace it with dynamic_cast and check the result for NULL, all sorts of nuances may be revealed.
For example, I had problems with casting the parent window to the class that it should have been. The study showed that in the version of the library for one of the platforms, the child class was wrapped in another parent, and such a cast caused a segfault...
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question