Nyaruko Nyaruko - 2 months ago 38
C++ Question

Qt: When shall I use Q_DECLARE_METATYPE?

The documentation said I need to Q_DECLARE_METATYPE a custom structure so it will work properly in a signal-slot.

But I have tried the following code which seems working fine?

#include <QMainWindow>

namespace Ui {
class MainWindow;
}
struct MyStruct
{
int a;
int b;
};

class MainWindow : public QMainWindow
{
Q_OBJECT

public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();

private:
Ui::MainWindow *ui;

signals:
void test(MyStruct);

public slots:
void tested(MyStruct);
private slots:
void on_pushButton_clicked();
};

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>
//------------------------CPP-------------------------------
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
connect(this, SIGNAL(test(MyStruct)),this,SLOT(tested(MyStruct)));
}

MainWindow::~MainWindow()
{
delete ui;
}

void MainWindow::tested(MyStruct t)
{
qDebug()<<t.a<<t.b;
}

void MainWindow::on_pushButton_clicked()
{
MyStruct t;
t.a=1;
t.b=2;
emit test(t);
}


The signal slot works without any problem, but in the following case:

struct SoundType
{
enum Type
{
Bip = 0,
LowBatt,
LowSat,
FarAway,
LostLink
};
};
Q_DECLARE_METATYPE(SoundType::Type)


it seems I do have to call the declaration inorder to use


SoundType::Type


in signal slot.

so in what case do I have to use Q_DECLARE_METATYPE in order to use a signal slot?

Answer

It doesn't have anything to do with signals and slots. Q_DECLARE_METATYPE needs to be used when you want to be able to store your own type in a QVariant

Note that this macro requires the type to be fully defined at the point where it is used; for pointer types, the pointer as well must be fully defined, so ideally you should place the macro right after your class declaration (once again, you only need it if you want to store your type objects in a QVariant).