Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Q_OBJECT and moc for inheritance

Tags:

c++

qt

I am working in a project where a Q_OBJECT macro is used in a class which I need to inherit.

The class where Q_OBJECT is already defined looks like this,

class cBaseObject : public QObject, public cinformation
{
    Q_OBJECT
    //...
    //...
}

I am creating a new class via public inheritance of cBaseObject. Should I need to write Q_OBJECT macro again? I tried with and without that macro and I am seeing no moc_XXX.cxx file is generated if I didn't include the QT_MACRO

class cEnhancedbaseObject : public cBaseObject
{
    Q_OBJECT   // if i didn't include this 
          //no moc__XXX.cxx file is  generated
} 

But when I inherit the class why the Q_OBJECT macro's functionality is also not inherited. Is it any problem if Q_OBJECT macro is defined twice, if it is inherited? How does the behavior of Q_OBJECT for multilevel inheritance. I have read that for multiple inheritance the QOBJECT class should be placed first. Is there anything similar for multilevel inheritance.

like image 879
evk1206 Avatar asked Dec 08 '15 15:12

evk1206


People also ask

When to use Q_OBJECT?

You should use the Q_OBJECT macro for any non-templated classes that derive from QObject . Besides signals and slots, the Q_OBJECT macro provides the meta object information that is associated with given class.

What does Qt moc do?

The Meta-Object Compiler, moc , is the program that handles Qt's C++ extensions. The moc tool reads a C++ header file. If it finds one or more class declarations that contain the Q_OBJECT macro, it produces a C++ source file containing the meta-object code for those classes.

What is moc files?

A MOC file is a source code file produced by the Qt development toolkit's Meta-Object Compiler. It contains meta-object code written in C++. MOC files are referenced in Qt . CPP files, to allow Qt's qmake compiler to correctly compile applications that include Q_OBJECT classes in a CPP file.


1 Answers

The presence of the Q_OBJECT macro marks the class for inclusion in Qt's meta-object system. If you want your class to have its own identity in this meta-object system, you must put the Q_OBJECT macro into it (and make sure it is directly or indirectly derived from QObject, naturally).

In your case of cBaseObject and cEnhancedbaseObject, if cEnhancedbaseObject does not include the Q_OBJECT macro, it will still work normally. However, as far Qt's meta-object system is concerned, objects of type cEnhancedbaseObject will be of meta-type cBaseObject. You can see that using such functions as myObject->metaObject()->className().

like image 79
Angew is no longer proud of SO Avatar answered Oct 23 '22 04:10

Angew is no longer proud of SO