生活随笔
收集整理的這篇文章主要介紹了
Qt中消息的机制原理
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
參考文章:https://blog.csdn.net/perfectguyipeng/article/details/78082360
原理基礎介紹
Qt中通過object類定義了connect函數,在connect函數中實現了將信號與槽函數的對應關系
這種對應關系記錄在元對象類中,信號函數的定義由元對象處理器定義,在這一步可以確定信號觸發時,槽函數被調用的過程。
主要理解一下幾個函數:
static void db_connect(Object*, const char*, Object*, const char*);
void MetaObject::active(Object* sender, int idx)
#ifndef DB_OBJECT
#define DB_OBJECT
#include <map>
# define db_slots
# define db_signals protected
# define db_emit
class Object;
struct MetaObject
{const char* sig_names
;const char* slts_names
;static void active(Object
* sender
, int idx
);
};
struct Connection
{Object
* receiver
;int method
;
};
typedef std
::multimap
<int, Connection
> ConnectionMap
;
typedef std
::multimap
<int, Connection
>::iterator ConnectionMapIt
;class Object
{static MetaObject meta
;void metacall(int idx
);
public:Object();virtual ~Object();static void db_connect(Object
*, const char*, Object
*, const char*);void testSignal();
db_signals
:void sig1();public db_slots
:void slot1();friend class MetaObject;
private:ConnectionMap connections
;
};
#endif
#include "object.h"#include <stdio.h>
#include <string.h>
Object
::Object()
{
}
Object
::~Object()
{
}
static int find_string(const char* str
, const char* substr
)
{if (strlen(str
) < strlen(substr
))return -1;int idx
= 0;int len
= strlen(substr
);bool start
= true;const char* pos
= str
;while (*pos
) {if (start
&& (!strncmp(pos
, substr
, len
))&& (pos
[len
] == '\0')){return idx
;}start
= false;if (*pos
== '\0') {idx
++;start
= true;}pos
++;}return -1;
}
void Object
::db_connect(Object
* sender
, const char* sig
, Object
* receiver
, const char* slt
)
{int sig_idx
= find_string(sender
->meta
.sig_names
, sig
);int slt_idx
= find_string(receiver
->meta
.slts_names
, slt
);if (sig_idx
== -1 || slt_idx
== -1) {perror("signal or slot not found!");}else {Connection c
= { receiver
, slt_idx
};sender
->connections
.insert(std
::pair
<int, Connection
>(sig_idx
, c
));}
}
void Object
::slot1()
{printf("hello dbzhang800!");
}
void MetaObject
::active(Object
* sender
, int idx
)
{ConnectionMapIt it
;std
::pair
<ConnectionMapIt
, ConnectionMapIt
> ret
;ret
= sender
->connections
.equal_range(idx
);for (it
= ret
.first
; it
!= ret
.second
; ++it
) {Connection c
= (*it
).second
;c
.receiver
->metacall(c
.method
);}
}
void Object
::testSignal()
{db_emit
sig1();
}
#include "object.h"
static const char sig_names
[] = "sig1";
static const char slts_names
[] = "slot1";
MetaObject Object
::meta
= { sig_names
, slts_names
};
void Object
::sig1()
{MetaObject
::active(this, 0);
}
void Object
::metacall(int idx
)
{switch (idx
) {case 0:slot1();break;default:break;};
}
#include "object.h"
int main()
{Object obj1
, obj2
;Object
::db_connect(&obj1
, "sig1", &obj2
, "slot1");obj1
.testSignal();return 0;;
}
總結
以上是生活随笔為你收集整理的Qt中消息的机制原理的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。