I have an event in one thread and need to invoke handler function in another. Usually I use function connect(), but in case of two threads I had an error:
QObject::connect: Cannot queue arguments of type 'QVector<unsigned char>'
(Make sure 'QVector<unsigned char>' is registered using qRegisterMetaType().)
I tried to use qRegisterMetaType(), but don't understood clearly how and where should I declare it. I wrote code sample, which just invoke execution in thread0 from thead1. I didn't include my attempts of using qRegisterMetaType() because they all failed =)
thread0.h:
#ifndef THREAD0_H
#define THREAD0_H
#include <QThread>
#include <QVector>
class thread0 : public QThread
{
Q_OBJECT
public:
thread0();
~thread0();
protected:
void run() Q_DECL_OVERRIDE;
public slots:
void printBuff(QVector<unsigned char> vec);
};
#endif // THREAD0_H
thread1.h:
#ifndef THREAD1_H
#define THREAD1_H
#include <QThread>
#include <QVector>
class thread1 : public QThread
{
Q_OBJECT
public:
thread1();
~thread1();
protected:
void run() Q_DECL_OVERRIDE;
signals:
void sendToPrint(QVector<unsigned char> vec);
};
#endif // THREAD1_H
main.cpp:
#include <QCoreApplication>
#include "thread0.h"
#include "thread1.h"
#include <QObject>
#include <QMetaType>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
thread0 *th0 = new thread0();
thread1 *th1 = new thread1();
QObject::connect(th1, &thread1::sendToPrint, th0, &thread0::printBuff);
th0->start();
th1->start();
return a.exec();
}
and thread1.cpp:
#include "thread1.h"
thread1::thread1()
{
}
thread1::~thread1()
{
}
void thread1::run()
{
QVector<unsigned char> vec = {0, 1, 2, 3};
emit sendToPrint(vec);
}
P.S. If I use direct connection code works.
QObject::connect(th1, &thread1::sendToPrint, th0, &thread0::printBuff, Qt::DirectConnection);
Aucun commentaire:
Enregistrer un commentaire