当前位置:网站首页>The difference of message mechanism between MFC and QT
The difference of message mechanism between MFC and QT
2022-07-02 17:22:00 【zhangchuan7758】
Windows news
Windows The message system of consists of the following 3 Part of it is made up of :
Message queue :Windows Ability to maintain a message queue for all applications , The application must get messages from the message queue , Then assign it to a form .
Message loop : Through this cycle mechanism , Applications retrieve messages from message queues , Then assign it to the appropriate window , Then continue to retrieve the next message from the message queue , Then assign to the appropriate window , In turn .
Window procedure : Every window has a window process , To receive Windows Messages delivered to the window , The task of the window process is to get the message and respond to it . Window procedure is a callback function , After processing a message , Usually give Windows A return value .
Windows There are two types of message queues in the system , One is the system message queue , The other is application message queuing . All input devices of the computer are controlled by Windows monitor , When an event happens ,Windows First put the input message into the system message queue , Then copy the input message to the corresponding application queue , The message loop in the application retrieves each message from its message queue and sends it to the corresponding window function . The occurrence of an event , Reaching the window function that handles it must go through the above process .
Windows The operating system maintains a message queue for each thread , When an event occurs , The operating system senses the occurrence of this event , And wrap it into a message and send it to the message queue , Application through GetMessage() The function obtains the message and coexists in a message structure , And then through a TranslateMessage() and DispatchMessage() Interpret and distribute messages .
MFC Message mechanism
MFC yes Windows One of the most popular class libraries for programming ,MFC The message mapping mechanism in is essentially a huge message and its processing function correspondence table ,MFC The nature of message mechanism is similar to Win identical , Only its processing is encapsulated --- Message mapping mechanism .
It is realized as follows :
hypothesis ParentWnd Processed 100 A message , And put this 100 A handler function is declared as a virtual function .
At this time, there is a subclass Childwnd Need to deal with 2 A message , in addition 98 One by ParentWnd Handle .
however ChildWnd The virtual table of still occupies 100 Function pointers , among 2 An implementation that points to itself , in addition 98 An implementation that points to the parent class .
MFC A handle and... Are maintained in the background C++ Object pointer comparison table , When you receive a message , Through the resource handle in the message structure ( Check the comparison table ) You can find the corresponding one C++ Object pointer , Then pass this pointer to the base class , The base class uses this pointer to call WindowProc() Function to process the message ,WindowProc() Call in function OnWndMsg() function , The real message routing and processing is done by OnWndMsg() Function completed . because WindowProc() and OnWndMsg() They're all virtual functions , And it is called with a pointer to a derived class object , From polymorphism, it is known that the subclass is always called . stay OnWndMsg() Function processing , Find the message map according to the message type , Judge whether the sent message has a response function , The specific way is to find the message response function declaration in the relevant header file and source file ( From the comment macro //{ {AFX_MSG(CDrawView)...//}}AFX_MSG Between looking for ), Message mapping ( From macro BEGIN_MESSAGE_MAP(...)....END_MESSAGE_MAP() Between looking for ), Finally, find the corresponding message processing function . Of course , If the message is not processed in the subclass , Then the message is handled by the base class .
MFC Is an event driven architecture . To do anything , Must respond to a specific message .Windows Thousands of messages are sent to applications , Therefore, users need to register and implement specific messages separately .
Qt news
QT It's a cross platform C++ GUI Application Architecture , It provides a rich set of widgets , With object-oriented 、 extensible 、 Real component programming and so on , What's more striking is that at present Linux The most popular in the world KDE The desktop environment is built on QT Based on the library .QT Support the following platforms :MS/WINDOWS-95、98、NT and 2000;UNIX/X11-Linux、Sun Solaris、HP-UX、Digital Unix、IBM AIX、SGI IRIX;EMBEDDED- Support framebuffer Of Linux platform . With KDE The rapid development and popularization of ,QT It's likely to be Linux When developing software on the window platform GUI The preferred .
and QT Cross platform C++ Graphical user interface Application development framework ,Qt The message mechanism of is based on SIGNAL() Send and SLOT() On the basis of acceptance . This mechanism is the core mechanism for establishing connections between objects . utilize SIGNAL() You can pass any parameter . It's very powerful . comparison MFC Come on ,QT The signal and slot mechanism are more powerful , And easy to reuse .
Qt Signal and slot mechanisms
QT The message mechanism of
Signals and slots
#include <QApplication>
#include <QPushButton>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QPushButton button("button_quit");
QObject::connect(&button, &QPushButton::clicked(), app, &QApplication::quit());
button.show();
return app.exec();
}
connect() The most commonly used general form of a function :
connect(sender, signal, receiver, slot);
Parameters :
sender: The object of the signal
signal: Sending signals from objects
receiver: The object receiving the signal
slot: The function that the receiving object needs to call after receiving the signal
remarks : Signal slot requires that the parameters of signal and slot are consistent , Consistency , Is the parameter type consistent . If it's not consistent , The permissible situation is , The slot function can have fewer parameters than the signal , even so , The order of the parameters of the slot function must also be consistent with the previous ones of the signal . This is because , You can choose to ignore the data from the signal in the slot function ( That is, the parameters of the slot function are less than those of the signal ), But it can't be said that the signal doesn't have this data at all , You're going to use it in the slot function ( That is, the parameters of the slot function are more than those of the signal , This is not allowed ).
1>. Format : connect( Signaler object ( The pointer ), &className::clicked(), Signal receiver object ( The pointer ), &classB::slot());
2>. Use of standard signal slot :
connect(sender, &Send::signal, receiver, &Receiver::slot)
Custom signals and slots
The declaration of the signal is made in the header file ,QT Of signals Keyword indicates entering the signal declaration area , Then you can declare your signal . The signal is from moc Automatic generation , So there's no need to cpp In the definition of , Just declare .
Slots are common C++ Member functions , Can be called normally , Their only particularity is that many signals can be associated with them . When the signal associated with it is transmitted , This slot will be called . The slot can have parameters , However, the parameters of the slot cannot have default values .
Slot functions are divided into three types , namely public slots、private slots and protected slots.
public slots: A slot declared in this area means that any object can connect a signal to it .
protected slots: The slot declared in this area means that the current class and its subclasses can connect signals to it .
private slots: The slot declared in this area means that only the class itself can connect signals to it .
#include <QObject>
// newspaper.h //
class Newspaper : public QObject
{
Q_OBJECT
public:
Newspaper(const QString & name) :
m_name(name)
{
}
void send()
{
emit newPaper(m_name);
}
signals:
void newPaper(const QString &name);
private:
QString m_name;
};
// reader.h //
#include <QObject>
#include <QDebug>
class Reader : public QObject
{
Q_OBJECT
public:
Reader() {}
void receiveNewspaper(const QString & name)
{
qDebug() << "Receives Newspaper: " << name;
}
};
// main.cpp //
#include <QCoreApplication>
#include "newspaper.h"
#include "reader.h"
int main(int argc, char *argv[])
{
QCoreApplication app(argc, argv);
Newspaper newspaper("Newspaper A");
Reader reader;
QObject::connect(&newspaper, &Newspaper::newPaper,
&reader, &Reader::receiveNewspaper);
newspaper.send();
return app.exec();
}
First of all to see Newspaper This class . This class inherits QObject class . Only inherited QObject Class in the class , To have the ability of a signal slot . therefore , In order to use the signal slot , Must inherit QObject. Anyone who QObject class ( Whether it's a direct subclass or an indirect subclass ), It should be written in the first line of code Q_OBJECT. Whether or not the signal slot is used , You should add this macro . The expansion of this macro will provide our class with a slot mechanism 、 Internationalization mechanism and Qt What is offered is not based on C++ RTTI The ability to reflect .
● Newspaper Class public and private The code blocks are relatively simple , It's just a new one signals.signals List of blocks , Is this kind of signal . A signal is a function name , The return value is void( Because the return value of the signal cannot be obtained , So there is no need to return any value ), Parameters are the data that the class needs to let the outside world know . Signal as function name , Don't need to cpp Add any implementation to the function .
●Newspaper Class send() The function is relatively simple , There is only one statement emit newPaper(m_name);.emit yes Qt Yes C++ An extension of , It's a keyword ( In fact, it is also a macro ).emit It means to send out , That is, send out newPaper() The signal . Interested recipients will pay attention to this signal , You may also need to know which newspaper sent the signal ? therefore , We will the actual newspaper name m_name Pass this signal as a parameter . When the receiver connects this signal , You can get the actual value through the slot function . This completes a transfer of data from the sender to the receiver .
● Reader Class is simpler . Because this class needs to accept signals , So we inherited it QObject, And added Q_OBJECT macro . Followed by the default constructor and an ordinary member function .Qt 5 in , Any member function 、static function 、 Global functions and Lambda Expressions can be used as slot functions . Different from the signal function , The slot function must complete the implementation code by itself . Slot functions are ordinary member functions , So as a member function , You're going to get public、private And so on .( If the signal is private Of , This signal cannot be connected outside the class , It doesn't make any sense .)
Custom message considerations :
● Both sender and receiver need to be QObject Subclasses of ( Of course , Slot functions are global functions 、Lambda Except when there is no receiver for expressions, etc );
● Use signals Mark the signal function , A signal is a function declaration , return void, There is no need to implement function code ;
● Slot functions are ordinary member functions , As a member function , Will receive public、private、protected Influence ;
● Use emit Send a signal in the right place ;
● Use QObject::connect() The function connects the signal to the slot .
● Any member function 、static function 、 Global functions and Lambda Expressions can be used as slot functions
Use of signals and slots
By calling connect Function to associate the signal of one object with the slot function of another object , So when the transmitter sends a signal , The receiver's slot function will be called .
● One signal can be connected to multiple slots
If that's the case , When this signal is transmitted , These slots will be executed one by one , But the order in which they are executed will be random 、 Not sure of , We can't artificially specify which one to execute first 、 Which post execution .
● Multiple signals can be connected to a slot
As long as any signal is sent out , This slot will be called .
● One signal can be connected to another signal
When the first signal comes out , The second signal is sent out . besides , This signal - The form of the signal and the signal - There's no difference in the form of grooves .
● Slots can be unlinked
It doesn't happen very often , Because when an object delete after ,Qt Automatically cancel all slots connected to this object .
● The parameter types of signal and slot should correspond
The parameter type of the signal can correspond to the parameter type of the slot , The parameters of the signal can be more than those of the slot , But not less , Otherwise the connection will fail .
边栏推荐
- Changwan group rushed to Hong Kong stocks: the annual revenue was 289million, and Liu Hui had 53.46% voting rights
- VMware install win10 image
- 什么是敏捷开发流程
- Usage of sprintf() function in C language
- 详细介绍scrollIntoView()方法属性
- &lt; IV & gt; H264 decode output YUV file
- 海思Hi3798MV100机顶盒芯片介绍[通俗易懂]
- Exploration of mobile application performance tools
- Amazon cloud technology community builder application window opens
- Qstype implementation of self drawing interface project practice (II)
猜你喜欢
Qwebengineview crash and alternatives
871. Minimum refueling times
Dgraph: large scale dynamic graph dataset
Easy language ABCD sort
Sword finger offer 21 Adjust the array order so that odd numbers precede even numbers
TCP congestion control details | 2 background
[essay solicitation activity] Dear developer, RT thread community calls you to contribute
Understand one article: four types of data index system
剑指 Offer 21. 调整数组顺序使奇数位于偶数前面
Notice on holding a salon for young editors of scientific and Technological Journals -- the abilities and promotion strategies that young editors should have in the new era
随机推荐
[leetcode] 14. Préfixe public le plus long
Amazon cloud technology community builder application window opens
电脑自带软件使图片底色变为透明(抠图白底)
One year is worth ten years
&lt; IV & gt; H264 decode output YUV file
2322. Remove the minimum fraction of edges from the tree (XOR and & Simulation)
福元医药上交所上市:市值105亿 胡柏藩身价超40亿
linux安装postgresql + patroni 集群问题
2、 Expansion of mock platform
酒仙网IPO被终止:曾拟募资10亿 红杉与东方富海是股东
[essay solicitation activity] Dear developer, RT thread community calls you to contribute
详细介绍scrollIntoView()方法属性
class和getClass()的区别
Believe in yourself and finish the JVM interview this time
社交元宇宙平台Soul冲刺港股:年营收12.8亿 腾讯是股东
上传代码到远程仓库报错error: remote origin already exists.
Ap和F107数据来源及处理
Sword finger offer 27 Image of binary tree
默认浏览器设置不了怎么办?
Does digicert SSL certificate support Chinese domain name application?