问题
Can I use a template type in any way as a slot or signal argument? As an example, I'm trying to define the following:
void exampleSignal(std::map<non_template_type_1,non_template_type_2> arg);
void exampleSlot(std::map<non_template_type_1,non_template_type_2> arg);
This results in the following during runtime:
QObject::connect: Cannot queue arguments of type
'std::map<non_template_type_1,non_template_type_2>'
(Make sure 'std::map<non_template_type_1,non_template_type_2>'
is registered using qRegisterMetaType().)
Trying to register std::map<non_template_type_1,non_template_type_2>
with Q_DECLARE_METATYPE()
results in compilation failure and apparently is not supported.
As a workaround, I'm using QVariantMap
instead of std::map
. But I really would like to know the correct way to solve this problem; one where it is not possible to modify the template classes.
Edit: I forgot to mention that the signal and slot are emitted and received in different threads. Apparently the runtime error doesn't occur in single-thread scenarios.
回答1:
As explained in this thread you can try using a typedef
, including the QMetaType
header and then using both Q_DECLARE_METATYPE
macro and the qRegisterMetaType
function (as implied by this thread on a similar issue).
回答2:
This works for me:
qRegisterMetaType< std::vector<float> >( "std::vector<float>" );
qRegisterMetaType< std::vector<int> >( "std::vector<int>" );
qRegisterMetaType< std::map<std::string,int64_t> >( "std::map<std::string,int64_t>" );
回答3:
There is no problem if you created the class like this and used the Qt moc compiler to create those QMetaObject
's automatically:
class MyClass : public QObject
{
Q_OBJECT
public:
explicit MyClass(QObject *parent = 0)
: QObject(parent)
{
}
public slots:
void exampleSlot(std::map<non_template_type_1,non_template_type_2> arg);
signals:
void exampleSignal(std::map<non_template_type_1,non_template_type_2> arg);
};
Of course you need to include QObject
and wherever std::map
is located at.
来源:https://stackoverflow.com/questions/26364024/how-to-use-template-types-as-slot-and-signal-parameters-in-multiple-threads