The QObject class is the base class of all Qt objects
Q_OBJECT Macro
The Q_OBJECT Macro is probably one of the weirdest things to whoever beginning to use Qt.
Qt QObject Class says:
The Q_OBJECT macro must appear in the private section of a class definition that declares its own signals and slots or that uses other services provided by Qt’s meta-object system.
class MyClass : public QObject
{
Q_OBJECT
public:
MyClass(QObject *parent = 0);
~MyClass();
signals:
void mySignal();
public slots:
void mySlot();
};
class MyClass : public QObject
{
Q_OBJECT
Q_PROPERTY(Priority priority READ priority WRITE setPriority)
Q_ENUMS(Priority)
public:
enum Priority { High, Low, VeryHigh, VeryLow };
MyClass(QObject *parent = 0);
~MyClass();
void setPriority(Priority priority) { m_priority = priority; }
Priority priority() const { return m_priority; }
private:
Priority m_priority;
So, it sounds like we need it to use signal and slot, and probably for other purposes (meta-object related) as well.
Another doc related to moc explains:
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. Among other things, meta-object code is required for the signals and slots mechanism, the run-time type information, and the dynamic property system.
moc limitations
Multiple Inheritance Requires QObject to Be First
// correct
class SomeClass : public QObject, public OtherClass
{
...
};
Function Pointers Cannot Be Signal or Slot Parameters
class SomeClass : public QObject
{
Q_OBJECT
public slots:
void apply(void (*apply)(List *, void *), char *); // WRONG
};
// instead you can do next
typedef void (*ApplyFunction)(List *, void *);
class SomeClass : public QObject
{
Q_OBJECT
public slots:
void apply(ApplyFunction, char *);
};
Nested Classes Cannot Have Signals or Slots
class A
{
public:
class B
{
Q_OBJECT
public slots: // WRONG
void b();
};
};
Signal/Slot return types cannot be references
Only Signals and Slots May Appear in the signals
and slots
Sections of a Class
QMetaObject
The QMetaObject class contains meta-information about Qt objects
The Qt Meta-Object System in Qt is responsible for the signals and slots inter-object communication mechanism, runtime type information, and the Qt property system. A single QMetaObject instance is created for each QObject subclass that is used in an application, and this instance stores all the meta-information for the QObject subclass. This object is available as QObject::metaObject().
This class is not normally required for application programming, but it is useful if you write meta-applications, such as scripting engines or GUI builders.
The functions you are most likely to find useful are these:
- className() returns the name of a class.
- superClass() returns the superclass’s meta-object.
- method() and methodCount() provide information about a class’s meta-methods (signals, slots and other invokable member functions).
- enumerator() and enumeratorCount() and provide information about a class’s enumerators.
- propertyCount() and property() provide information about a class’s properties.
- constructor() and constructorCount() provide information about a class’s meta-constructors.
The index functions indexOfConstructor(), indexOfMethod(), indexOfEnumerator(), and indexOfProperty() map names of constructors, member functions, enumerators, or properties to indexes in the meta-object. For example, Qt uses indexOfMethod() internally when you connect a signal to a slot.
Classes can also have a list of name—value pairs of additional class information, stored in QMetaClassInfo objects. The number of pairs is returned by classInfoCount(), single pairs are returned by classInfo(), and you can search for pairs with indexOfClassInfo().
Q_INVOKABLE void fun();
emmiter->metaObject()->method(emmiter->metaObject()->indexOfMethod("fun()")).invoke(emmiter,Qt::ConnectionType::DirectConnection,Q_ARG(QObject*, emmiter));
private slots:
void MySlot(QObject* obj);
QMetaObject::invokeMethod(emmiter,"MySlot",Qt::ConnectionType::DirectConnection,Q_ARG(QObject*, emmiter));
//invoke methods defined with public slots or private slots or Q_INVOKABLE
class Test:QObject
{
Q_OBJECT
public:
enum Myen{A,B,C};
Q_ENUM(Myen);
Test();
Q_INVOKABLE void fun(Test::Myen en);
};
Q_DECLARE_METATYPE(Test::Myen);
bool b=QMetaObject::invokeMethod(this,"fun",Qt::ConnectionType::QueuedConnection,Q_ARG(Test::Myen,A));
//call fun function Test::A
QObject Structure
QObjects organize themselves in object trees. When you create a QObject with another object as parent, the object will automatically add itself to the parent’s children() list. The parent takes ownership of the object; i.e., it will automatically delete its children in its destructor. You can look for an object by name and optionally type using findChild() or findChildren().
QObject(QObject *parent = nullptr)
parent() const
setParent(QObject *parent)
objectName() const
setObjectName(const QString &name)
findChild(const QString &name = QString(), Qt::FindChildOptions options = Qt::FindChildrenRecursively)
findChildren(const QString &name = QString(), Qt::FindChildOptions options = Qt::FindChildrenRecursively)
children() const
inherits check
QTimer *timer = new QTimer; // QTimer inherits QObject
timer->inherits("QTimer"); // returns true
timer->inherits("QObject"); // returns true
timer->inherits("QAbstractButton"); // returns false
// QVBoxLayout inherits QObject and QLayoutItem
QVBoxLayout *layout = new QVBoxLayout;
layout->inherits("QObject"); // returns true
layout->inherits("QLayoutItem"); // returns true (even though QLayoutItem is not a QObject)
QObject *obj = new QTimer; // QTimer inherits QObject
QTimer *timer = qobject_cast<QTimer *>(obj);
// timer == (QObject *)obj
QAbstractButton *button = qobject_cast<QAbstractButton *>(obj);
// button == nullptr
Dynamic Properties (QMetaProperty)
class MyClass: public QObject
{
Q_OBJECT
Q_PROPERTY(Priority priority READ priority WRITE setPriority NOTIFY priorityChanged)
public:
MyClass(QObject *parent = 0);
~MyClass();
enum Priority { High, Low, VeryHigh, VeryLow };
Q_ENUM(Priority)//registered as QMetaEnum
void setPriority(Priority priority)// is not diffrent if private or public
{
m_priority = priority;
emit priorityChanged(priority);
}
Priority priority() const
{ return m_priority; }
signals:
void priorityChanged(Priority);
private:
Priority m_priority;
};
MyClass *myinstance = new MyClass;
QObject *object = myinstance;
myinstance->setPriority(MyClass::VeryHigh);
object->setProperty("priority", "VeryHigh");
property(const char *name) const//call read function or get value of member
bool QObject::setProperty(const char *name, const QVariant &value)//call write function or set value to member
class Test:QObject
{
Q_OBJECT
public:
enum Myen{A,B,C};
Q_ENUM(Myen);
Test();
Q_INVOKABLE void fun(Test::Myen en);// once you declare metataype as Test::Myen the argument should to be Test::Myen
};
Q_DECLARE_METATYPE(Test::Myen);
class A{
public:
operator QString(){
return QStringLiteral("A");
}
};
Q_DECLARE_METATYPE(A);
Test::Test()
{
QString retval;
bool b=QMetaObject::invokeMethod(this,"fun",Qt::ConnectionType::QueuedConnection,Q_ARG(Test::Myen,A));
qDebug()<<"end constructor";
}
void Test::fun(Test::Myen en)
{
qDebug()<<"call fun function"<<en;
}
Signals and Slots
#include <QApplication>
#include <QPushButton>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QPushButton *quitButton = new QPushButton("Quit");
QObject::connect(quitButton, SIGNAL(clicked()),
&app, SLOT(quit()));
quitButton->show();
return app.exec();
}
A signal can also be connected to another signal:
class MyWidget::public QWidget
{
Q_OBJECT
public:
MyWidget();
signals:
void buttonClicked();
private:
QPushButton *myButton;
};
MyWidget::MyWidget()
{
myButton = new QPushButton(this);
connect(myButton, SIGNAL(clicked()),
this, SIGNAL(buttonClicked()));
}
The signal must be a function declared as a signal in the header. The slot function can be any member function that can be connected to the signal. A slot can be connected to a given signal if the signal has at least as many arguments as the slot, and there is an implicit conversion between the types of the corresponding arguments in the signal and the slot.
QLabel *label = new QLabel;
QLineEdit *lineEdit = new QLineEdit;
QObject::connect(lineEdit, &QLineEdit::textChanged,
label, &QLabel::setText);
connect(const QObject *sender, const char *signal, const QObject *receiver, const char *method, Qt::ConnectionType type = Qt::AutoConnection) |
connect(const QObject *sender, const QMetaMethod &signal, const QObject *receiver, const QMetaMethod &method, Qt::ConnectionType type = Qt::AutoConnection) |
connect(const QObject *sender, PointerToMemberFunction signal, const QObject *receiver, PointerToMemberFunction method, Qt::ConnectionType type = Qt::AutoConnection) |
connect(const QObject *sender, PointerToMemberFunction signal, Functor functor) |
connect(const QObject *sender, PointerToMemberFunction signal, const QObject *context, Functor functor, Qt::ConnectionType type = Qt::AutoConnection) |
enum Qt::ConnectionType
This enum describes the types of connection that can be used between signals and slots. In particular, it determines whether a particular signal is delivered to a slot immediately or queued for delivery at a later time.
Constant |
---|
Qt::AutoConnection (Default) If the receiver lives in the thread that emits the signal, Qt::DirectConnection is used. Otherwise, Qt::QueuedConnection is used. The connection type is determined when the signal is emitted. |
Qt::DirectConnection The slot is invoked immediately when the signal is emitted. The slot is executed in the signalling thread. |
Qt::QueuedConnection The slot is invoked when control returns to the event loop of the receiver’s thread. The slot is executed in the receiver’s thread. |
Qt::BlockingQueuedConnection Same as Qt::QueuedConnection, except that the signalling thread blocks until the slot returns. This connection must not be used if the receiver lives in the signalling thread, or else the application will deadlock. |
Qt::UniqueConnection This is a flag that can be combined with any one of the above connection types, using a bitwise OR. When Qt::UniqueConnection is set, QObject::connect() will fail if the connection already exists (i.e. if the same signal is already connected to the same slot for the same pair of objects). This flag was introduced in Qt 4.6. |
#include <QtCore>
class Test : public QObject
{
Q_OBJECT
public:
explicit Test(QObject *parent = nullptr);
signals:
void MySignal();
public:
void EmitSignal();
public slots://not necesorry only if you wnat to use it as SLOT(MySlot())
void MySlot();
};
#include "test.h"
Test::Test(QObject *parent) : QObject(parent)
{
}
void Test::EmitSignal(){
emit this->MySignal();
qDebug()<<"signal is emmited";
}
void Test::MySlot(){
qDebug()<<"slot is called"<<sender();
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
Test emmiter,reciver;
QObject::connect(&emmiter,&Test::MySignal,&reciver,&Test::MySlot,Qt::ConnectionType::QueuedConnection);
//print signal is emmited then slot is called
QObject::connect(&emmiter,&Test::MySignal,&reciver,&Test::MySlot,Qt::ConnectionType::DirectConnection);
//print slot is called then signal is emmited
emmiter.EmitSignal();
return a.exec();
}
there are many ways to add signal and slot to connect
QObject::connect(&emmiter,SIGNAL(MySignal()),&reciver,SLOT(MySlot()));//slot here should to be Q_INVOKABLE or public private slots:
QObject::connect(&emmiter,&Test::MySignal,&reciver,&Test::MySlot)// slot here can be any function member of object
disconnect
disconnect(const QObject *sender, const char *signal, const QObject *receiver, const char *method) |
disconnect(const QObject *sender, const QMetaMethod &signal, const QObject *receiver, const QMetaMethod &method) |
disconnect(const QMetaObject::Connection &connection) |
disconnect(const QObject *sender, PointerToMemberFunction signal, const QObject *receiver, PointerToMemberFunction method) |
before we were use public static method to connect and disconnect but actually you can use public non-static members
disconnect(const char *signal = nullptr, const QObject *receiver = nullptr, const char *method = nullptr) |
connect(const QObject *sender, const char *signal, const char *method, Qt::ConnectionType type = Qt::AutoConnection) |
disconnect(const QObject *receiver, const char *method = nullptr) const |
void blockSignals(bool block) // non-static member to block any signal come from this object
bool signalsBlocked() const// to check if signals comming from this object is blocked or not
int receivers(const char *signal) const //protected method number of recivers
QObject * sender() const // protected method can use it inside any slot to get the sender object
int senderSignalIndex() const //meta-method index of the signal that called the currently executing slot
QCoreApplication a(argc, argv);
Test *emmiter=new Test{} ,*reciver=new Test{};
QObject::connect(emmiter,&Test::destroyed,reciver,&Test::MySlot);
qDebug()<<emmiter;
delete emmiter;
return a.exec();
//===============================
void Test::MySlot(QObject* obj){
qDebug()<<"slot is called \n"<<obj;
}
QSignalMapper
QGridLayout *gridLayout = new QGridLayout(this);
QSignalMapper *mapper = new QSignalMapper(this);
for(int row = 0; row < 3; ++row) {
for(int column = 0; column < 3; ++column) {
QPushButton *button = new QPushButton(" ");
gridLayout->addWidget(button, row, column);
m_board.append(button);
mapper->setMapping(button, m_board.count() - 1);
connect(button, SIGNAL(clicked()), mapper, SLOT(map()));
}
}
connect(mapper, SIGNAL(mapped(int)),
this, SLOT(handleButtonClick(int)));
QObject predefined signals and slots
deleteLater()
destroyed(QObject *obj = nullptr)
objectNameChanged(const QString &objectName)
Events System
Qt creates an event object to represent it by constructing an instance of the appropriate QEvent subclass, and delivers it to a particular instance of QObject (or one of its subclasses) by calling its event() function.
This function does not handle the event itself; based on the type of event delivered, it calls an event handler for that specific type of event, and sends a response based on whether the event was accepted or ignored.
bool MyWidget::event(QEvent *event)
{
if (event->type() == QEvent::KeyPress) {
QKeyEvent *ke = static_cast<QKeyEvent *>(event);
if (ke->key() == Qt::Key_Tab) {
// special tab handling here
return true;
}
} else if (event->type() == MyCustomEventType) {
MyCustomEvent *myEvent = static_cast<MyCustomEvent *>(event);
// custom event handling here
return true;
}
return QWidget::event(event);
}
Note that event() is still called for all of the cases not handled, and that the return value indicates whether an event was dealt with; a true
value prevents the event from being sent on to other objects.
protected:
bool event(QEvent *event) override{
qDebug()<<"call event \n";
QObject::event(event);//call timerEvent
return false;
}
void timerEvent(QTimerEvent *event) override{
qDebug()<<"call timer event \n";
}
bool eventFilter(QObject *watched, QEvent *event) override{
//watched = pointer to object carch event
qDebug()<<"call event filter \n";
return false; // false meen can call event function
}
Test t;
t.startTimer(1000);
t.installEventFilter(&t);
call event filter
call event
call timer event
When the filter object’s eventFilter() implementation is called, it can accept or reject the event, and allow or deny further processing of the event. If all the event filters allow further processing of an event (by each returning false
), the event is sent to the target object itself. If one of them stops processing (by returning true
), the target and any later event filters do not get to see the event at all.
Sending Events
Many applications want to create and send their own events. You can send events in exactly the same ways as Qt’s own event loop by constructing suitable event objects and sending them with QCoreApplication::sendEvent() and QCoreApplication::postEvent().
sendEvent() processes the event immediately. When it returns, the event filters and/or the object itself have already processed the event. For many event classes there is a function called isAccepted() that tells you whether the event was accepted or rejected by the last handler that was called.
postEvent() posts the event on a queue for later dispatch. The next time Qt’s main event loop runs, it dispatches all posted events, with some optimization. For example, if there are several resize events, they are compressed into one. The same applies to paint events: QWidget::update() calls postEvent(), which eliminates flickering and increases speed by avoiding multiple repaints.
postEvent() is also used during object initialization, since the posted event will typically be dispatched very soon after the initialization of the object is complete. When implementing a widget, it is important to realize that events can be delivered very early in its lifetime so, in its constructor, be sure to initialize member variables early on, before there’s any chance that it might receive an event.
To create events of a custom type, you need to define an event number, which must be greater than QEvent::User, and you may need to subclass QEvent in order to pass specific information about your custom event. See the QEvent documentation for further details.
Q_GADGET
The Q_GADGET macro is a lighter version of the Q_OBJECT macro for classes that do not inherit from QObject but still want to use some of the reflection capabilities offered by QMetaObject. Just like the Q_OBJECT macro, it must appear in the private section of a class definition.
Q_GADGETs can have Q_ENUM, Q_PROPERTY and Q_INVOKABLE, but they cannot have signals or slots.
Q_GADGET makes a class member, staticMetaObject
, available. staticMetaObject
is of type QMetaObject and provides access to the enums declared with Q_ENUMS.
links
https://doc.qt.io/qt-5/qobject.html
https://doc.qt.io/qt-5/qmetaobject.html