Qt registered custom type

1. The necessity of custom type registration

If you want to use a custom type in a Qt signal slot, you need to pay attention to the use of qRegisterMetaType to register the custom type. Of course, if you use the custom type signal/slot to pass when it is not cross-threaded, there may be no problems; once cross-threading is involved It is very easy to make mistakes. Recall that the function of the signal slot is to communicate between objects, and it will inevitably cross threads. It is recommended that when using a custom type to communicate with a signal slot, it is best to use qRegisterMetaType() to set the custom type first. Register to avoid errors.


2. How to use qRegisterMetaType

Summarizing the usage of qRegisterMetaType is as follows:
1. Registration location: Before using this type of cross-thread signal/slot for the first time, it is generally registered in the constructor of the current class;
2. Registration method: contains at the top of the current class: #include <QMetaType>, Add code to the constructor: qRegisterMetaType<MyClass>("Myclass");
3. The reference type of Myclass needs to be registered separately:qRegisterMetaType<MyClass>("Myclass&");

If it is a self-defined type, it is not so simple if you want to use signal/slot to pass it. If used directly, the following error will occur:
QObject::connect: Cannot queue arguments of type'TextAndNumber' (Make sure'TextAndNumber' is registed using qRegisterMetaType().)

Reason: When a signal is put in the queue (queued), its parameters (arguments) will also be put in the queue together (queued), which means that the parameters need to be copied before being sent to the slot. Stored in the queue (queue); in order to be able to store these parameters (argument) in the queue, Qt needs to construct, destruct, copy these objects, and in order to let Qt know how to do these things, the types of parameters need to use qRegisterMetaType to Register (as explained in the error message).

Steps: (Take custom TextAndNumber type as an example)

  1. Customize a type and include at the top of this type:
	#include <QMetaType>
  1. After the type definition is complete, add a statement:
	Q_DECLARE_METATYPE(TextAndNumber);
  1. Register this type in the main() function:
	qRegisterMetaType<TextAndNumber>("TextAndNumber");

If you still want to use this type of reference, you can also register:

	qRegisterMetaType<TextAndNumber>("TextAndNumber&");

Guess you like

Origin blog.csdn.net/locahuang/article/details/110221959