MasterMastic
MasterMastic

Reputation: 21286

Non-Qt Base Classes

I'm using Qt (which I'm new to) 4.8.2, with Visual Studio, and I have created a base class named "Contact". I don't want this class to be Qt-exclusive, so my intention was to make another class "QContact" that will inherit "Contact", and QObject and deal with all the Qt-related business, such as the Q_OBJECT macro etc.

Unfortunately when I inherited, the build failed, saying:

moc_QContact.cpp(53): error C2039: 'staticMetaObject' : is not a member of 'Contact'
moc_QContact.cpp(75): error C2039: 'qt_metacast' : is not a member of 'Contact'
moc_QContact.cpp(80): error C2039: 'qt_metacall' : is not a member of 'Contact'

I did a little research on the web and found out that you can't derive a Qt class from non-Qt class. so to fix it, "Contact" could inherit "QObject" (I tried, it worked). but doing so will make it exclusive to Qt which is my problem.

So what I ask is this: How can you make a non-Qt base class for a Qt class?

Thank you.

Upvotes: 51

Views: 17880

Answers (2)

From An Introduction To Design Patters in C++ with Qt Chapter 8.4:

To help ensure that moc processes each QObject-derived class in the project, following are some guidelines for writing: C++ code and qmake project files:

• Each class definition should go in its own .h file.

• Its implementation should go in a corresponding .cpp file.

• The header file should be “wrapped” (e.g., with #ifndef) to avoid multiple inclusion. • Each .cpp file should be listed in the SOURCES variable of the project file; otherwise it will not be compiled.

• Each header file should be listed in the HEADERS variable of the .pro file. Without this, moc will not preprocess the file.

• The Q_OBJECT macro must appear inside the class definition of each QObject derived header file so that moc knows to generate code for it.

Upvotes: -1

Johannes Schaub - litb
Johannes Schaub - litb

Reputation: 506985

You can derive your class from QObject and from other classes that don't derive from it, but QObject needs to be the first base class in the base classes list.

So this is wrong:

class QContact: public Contact, public QObject {};

You need to write it as

class QContact: public QObject, public Contact {};

Upvotes: 106

Related Questions